【问题标题】:python 3 dictionary key to a string and value to another stringpython 3字典键到一个字符串和值到另一个字符串
【发布时间】:2019-06-26 12:54:52
【问题描述】:

如果有字典:

dict={'a':'b'}

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

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

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

【问题讨论】:

  • 你要找的方法是keys()而不是key()
  • print(str(dict.keys())) 显示a 你需要使用keys() 而不是key()
  • dict 作为变量名是很不幸的,因为dict 是一个类型名。

标签: python string dictionary


【解决方案1】:

使用dict.items()

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

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

我将d.items() 转换为列表,并选择了它的0 索引,您也可以将其转换为迭代器,并使用next 选择它的第一个:

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

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

您还可以使用dict.keys() 检索所有字典键,并选择其第一个键。并使用dict.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

上述方法不能确保检索字符串,它们将返回键的实际类型和值。您可以将它们显式转换为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'>

现在,keyvalue 都是 str。虽然 dict 中的实际值是 int

免责声明:如果字典有多个键值对,这些方法将选择第一个键、值对,而忽略其他的。如果字典为空,它将不起作用。如果您需要的解决方案在字典中有多个值的情况下会失败,那么@SylvainLeroux's answer 是您应该寻找的解决方案。

【讨论】:

    【解决方案2】:
    >>> d = { 'a': 'b' }
    >>> d.items()
    dict_items([('a', 'b')])
    

    此时,您可以使用解构赋值来获取您的值:

    >>> [[key, value]] = d.items()
    >>> key
    'a'
    >>> value
    'b'
    

    此解决方案的一个优点是它将fail in case of d containing several entries, instead of silently ignoring the issue

    >>> d = { 'a': 'b', 'c':'d' }
    >>> [[key, value]] = d.items()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: too many values to unpack (expected 1)
    

    最后,如果您需要确保keyvalue 是字符串,您可以添加一个列表推导:

    >>> d = { 1: 2 }
    >>> [[key, value]] = ((str(key), str(value)) for key,value in d.items())
    >>> key
    '1'
    >>> value
    '2'
    

    【讨论】:

    • 不错!关键字:解构赋值
    【解决方案3】:

    要在没有任何导入的情况下在 dict 中有多个键的解决方案,我使用了以下轻型解决方案。

    dict={'a':'b','c':'d'}
    
    keys = "".join(list(dict.keys()))
    values = "".join(list(dict.values()))
    

    【讨论】:

      【解决方案4】:

      列出键和值:

      dict={'a':'b'}
      
      keys = list(dict.keys())
      values = list(dict.values())
      

      然后制作变量:

      key = keys[0]
      value = values[0]
      

      【讨论】:

        【解决方案5】:

        https://docs.python.org/3/library/stdtypes.html#typesmapping

        您要查找的方法是keys()values()

        【讨论】:

          猜你喜欢
          • 2017-03-14
          • 1970-01-01
          • 2020-04-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-25
          相关资源
          最近更新 更多