python 3字典键到一个字符串,值到另一个字符串 [英] python 3 dictionary key to a string and value to another string

查看:180
本文介绍了python 3字典键到一个字符串,值到另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有字典:

dict={'a':'b'}

在python 3中,我想将此字典键转换为字符串,并将其值转换为另一个字符串:

in python 3, i would like to convert this dictionary key to a string and its value to another string:

print(key)
key='a'
print(type(key))
str

print(value)
value='a'
print(type(value))
str

一些尝试:

str(dict.key()) # returns 'dict' object has no attribute 'key'

json.dump(dict) # returns {'a':'b'} in string, but hard to process

任何简单的解决方案吗?谢谢!

Any easy solution? Thank you!

推荐答案

使用 dict.items()

您可以使用 dict.items() dict.iteritems() (对于python 2),它返回键和值对,并且您只需简单地选择它的第一个即可。

You can use dict.items() (dict.iteritems() for python 2), it returns pairs of keys and values, and you can simply pick its first.

>>> d = { 'a': 'b' }
>>> key, value = list(d.items())[0]
>>> key
'a'
>>> value
'b'

我转换了 d.items() 到列表,并选择其 0 索引,您还可以将其转换为迭代器,并使用首先选择下一个

I converted d.items() to a list, and picked its 0 index, you can also convert it into an iterator, and pick its first using next:

>>> key, value = next(iter(d.items()))
>>> key
'a'
>>> value
'b'

使用 dict.keys() dict.values()

您还可以使用 dict.keys()检索所有字典键,然后选择它的第一个键。并使用 dict.values()检索所有字典值:

You can also use dict.keys() to retrieve all of the dictionary keys, and pick its first key. And use dict.values() to retrieve all of the dictionary values:

>>> key = list(d.keys())[0]
>>> key
'a'
>>> value = list(d.values())[0]
>>> value
'b'

在这里,您可以使用 next(也是iter(...))

>>> key = next(iter(d.keys()))
>>> key
'a'
>>> value = next(iter(d.values()))
'b'

确保获取 str

Ensure getting a str:

上述方法不能确保检索字符串,他们将返回键的实际类型和值。您可以将它们显式转换为 str

The above methods don't ensure retrieving a string, they'll return whatever is the actual type of the key, and value. You can explicitly convert them to str:

>>> d = {'some_key': 1}
>>> key, value = next((str(k), str(v)) for k, v in d.items())
>>> key
'some_key'
>>> value
'1'
>>> type(key)
<class 'str'>
>>> type(value)
<class 'str'>

现在,同时使用 key str 。尽管dict的实际值是 int

Now, both key, and value are str. Although actual value in dict was an int.

免责声明:这些方法可以选择第一个键,字典的值对(如果它具有多个键值对),而忽略其他键对。如果字典为空,它将不起作用。如果您需要一个在字典中存在多个值而导致失败的解决方案,请 @ SylvainLeroux的答案是您应该寻找的答案。

Disclaimer: These methods will pick first key, value pair of dictionary if it has multiple key value pairs, and simply ignore others. And it will NOT work if the dictionary is empty. If you need a solution which simply fails if there are multiple values in the dictionary, @SylvainLeroux's answer is the one you should look for.

这篇关于python 3字典键到一个字符串,值到另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆