简体   繁体   English

将字典的值转换为键值对

[英]Convert values of a dictionary into key value pair

I have a sample dictionary我有一个示例字典

sample_dict = [{"id":1, "count":10},
               {"id":2, "count":20},
               {"id":3, "count":30}]

I want something like this我想要这样的东西

sample_dict = [{1: 10}, {2: 20}, {3: 30}]

how can I do this optimally?我怎样才能最好地做到这一点?

You probably want a single object like this:你可能想要一个这样的对象:

sample_dict = [{"id":1, "count":10},{"id":2, "count":20},{"id":3, "count":30}]

out = { o['id']: o['count'] for o in sample_dict }
print(out) # {1: 10, 2: 20, 3: 30}
print(out[2]) # 20

Note that although the id and count values are in-order, this is not a requirement for this method.请注意,尽管idcount值是有序的,但这不是此方法的要求。 So long as the id values are unique, this will work.只要id值是唯一的,这就会起作用。

sample_dict = [{"id":1, "count":10},
               {"id":2, "count":20},
               {"id":3, "count":30}]

output = []
for elem in sample_dict:
    new_dict = {elem["id"]: elem["count"]}
    output.append(new_dict)

Printing output will return打印输出将返回

print(output)

[{1: 10}, {2: 20}, {3: 30}]

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

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