简体   繁体   English

具有多个键值对的字典列表

[英]Flatten list of dictionaries with multiple key, value pairs

I have a list of dictionaries with multiple KVP each我有一个字典列表,每个字典都有多个 KVP

list_dict = [{'id': 1, 'name': 'sana'}, {'id': 2, 'name': 'art'}, {'id': 3, 'name': 'tiara'}]

I want to transform this into this format:我想将其转换为这种格式:

final_dict = {1: 'sana', 2: 'art', 3: 'tiara'}

I've been trying dict comprehensions but it does not work.我一直在尝试dict理解,但它不起作用。 Here's the best that I could do:这是我能做的最好的:

{k:v for d in list_dict for k, v in d.items()}

You don't need d.items() , you can just access the id and name properties of each dict.你不需要d.items() ,你可以只访问每个字典的idname属性。

{d['id']: d['name'] for d in list_dict}

for each element of the list you want the d["id"] to be the key and d["name"] to be the value, so the dictionary comprehension would look like this:对于列表中的每个元素,您希望d["id"]成为键, d["name"]成为值,因此字典理解将如下所示:

{d["id"]: d["name"] for d in list_dict}

You can try你可以试试

final_dict={} 
for dico in list_dict:
    final_dict[dico['id']] = dico['name'] 

There's probably a few different ways you can do this.可能有几种不同的方法可以做到这一点。 Here's a nice simple way of doing it using a pandas dataframe:这是使用 pandas dataframe 执行此操作的一种非常简单的方法:

import pandas as pd
df = pd.DataFrame(list_dict) # <- convert to dataframe
df = df.set_index('id') # <- set the index to the field you want as the key
final_dict = df['name'].to_dict() # <- convert the series 'name' to a dict
print(final_dict)

{1: 'sana', 2: 'art', 3: 'tiara'}

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

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