简体   繁体   English

Python-将字典转换为具有列表值的字典

[英]Python- Convert dictionary to dictionary with list value

I wanna convert dictionary to dictionary with list value 我想将字典转换为具有列表值的字典

I wanna convert : 我想转换:

 f= {24149423: 59, 22621293.0: 367562.0, 24144369.0: 405017.0, 22662739.0: 276484.0, 22470388.0: 410315.0, 22624054.0: 398444.0, 22614201.0: 380106.0, 22564857.0: 90756.0, 22619259.0: 382386.0, 22692381.0: 388392.0}

to dictionary with list value 用列表值字典

b =  {90756.0: [22564857.0], 388392.0: [22692381.0], 367562.0: [22621293.0], 410315.0: [22470388.0], 398444.0: [22624054.0], 382386.0: [22619259.0], 405017.0: [24144369.0], 276484.0: [22662739.0], 59: [24149423], 380106.0: [22614201.0]}

I try to write it this way: 我尝试这样写:

from collections import defaultdict 

b = defaultdict(list)

for key, value in sorted(f.iteritems()):
    b[value].append(key)

I used map as well. 我也使用地图。

b = map(lambda k, v: f.update({k: v}), keys, values)

But none of these work. 但是这些都不起作用。

for key in f.keys():
    f[key] = [f[key]]

Also Works .... 也可以....

Use a dict comprehension , like this: 使用dict理解 ,如下所示:

b = { v: [k] for k,v in f.items() }

[k] is a one-element list containing the key, v is the value, which now plays the rold of the key in the resulting dictionary. [k]是一个包含键的单元素列表, v是值,它现在在结果字典中播放键的序号。

f= {24149423: 59, 22621293.0: 367562.0, 24144369.0: 405017.0, 22662739.0: 276484.0, 22470388.0: 410315.0, 22624054.0: 398444.0, 22614201.0: 380106.0, 22564857.0: 90756.0, 22619259.0: 382386.0, 22692381.0: 388392.0}
new_f = {x:[f[x]] for x in f}

Using dict comprehension you can edit it pretty fast. 使用dict理解,您可以快速编辑它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM