将字典中的列表转换为字符串?

时间:2015-05-28 10:42:52

标签: python string list dictionary

我的字典看起来像这样:

dict = {1092267: [0.187], 524292: [-0.350], 524293: [0.029], 524294: [0.216]}

所以在列表中有一个ID后跟一个值。我希望列表是这样的字符串:

dict = {1092267: '0.187', 524292: '-0.350', 524293: '0.029', 524294: '0.216'}

我该怎么做?

编辑:给出的所有答案都给了我错误:当我使用更大的列表时,'str'对象没有属性'items'

5 个答案:

答案 0 :(得分:4)

iteritems()dict comprehensions救援:

bslots = dict((x, a.index(x)) for x in a if x in b)
bslotsSorted = sorted(bslots.keys(), key=lambda y: b.index(y))
indexes = sorted(bslots.values())
for x,y in zip(bslotsSorted, indexes):
  a[y] = x

但请不要使用d = {k: str(v[0]) for k,v in d.iteritems()} 作为变量的名称

答案 1 :(得分:1)

使用iteritemsdict comprehension。不要使用dict作为变量名称

>>>{i:str(j[0]) for i,j in dict.iteritems() }
{524292: '-0.35', 524293: '0.029', 524294: '0.216', 1092267: '0.187'}

Python3

>>>{i:str(j[0]) for i,j in dict.items() }

答案 2 :(得分:0)

尝试这个。

flag = list.indexOf('VALUE') > -1

输出:

for key, value in mydict.items():
    mydict.update({key: str(value[0])})

答案 3 :(得分:0)

for key, value in dict.viewitems():
    dict[key] = str(value[0])

输出:

{1092267: '0.187', 524292: '-0.35', 524293: '0.029', 524294: '0.216'}

答案 4 :(得分:0)

我无法发表评论,但罗曼·佩卡尔(Roman Pekar)的答案是正确的答案。但这在Python 3.x中不起作用,因为d.items现在可以完成以前使用的d.iteritems了:

d = {k: str(v[0]) for k,v in d.iteritems()}

因此,Python 3中的解决方案是:

d = {k: str(v[0]) for k,v in d.items()}

为了防止出错,您可能想检查您要更改的值是否实际上是一个列表:

d = {k: str(v[0]) for k,v in d.items() if isinstance(v, (list,))}

输出:

{1092267: '0.187', 524292: '-0.35', 524293: '0.029', 524294: '0.216'}
相关问题