[英]Python List of Dictionaries to new Dictionary or List
Pardon the noob question, I am new to Python.请原谅菜鸟问题,我是 Python 的新手。
I am working with a list of dictionaries:我正在使用字典列表:
dataset = [
{'id':1,'dateCollected':'2021-03-02','orders':7},
{'id':2,'dateCollected':'2021-03-03','orders':8},
]
.... this goes on for 50 records.... .... 这持续了 50 条记录....
I would like to a make a for loop that iterates through every dictionary in the list and adds certain key-value pairs to a new dictionary.我想做一个 for 循环,遍历列表中的每个字典,并将某些键值对添加到新字典中。
For Example:例如:
match_history_data = {}
for i in dataset:
match_history_data['DateCollected'] = i['dateCollected']
match_history_data['Orders'] = i['orders']
print(match_history_data)
results in:结果是:
{'DateCollected': '2021-03-03', 'Orders': 8}
I would like the result to be:我希望结果是:
{'DateCollected':'2021-03-02','Orders':7},
{'DateCollected':'2021-03-03','Orders':8}
This works how I want it to, but only for the first iteration in the for loop.这适用于我想要的方式,但仅适用于 for 循环中的第一次迭代。 How do I get around this so that it goes thru all the records in 'dataset', and creates the new list or dictionary?我该如何解决这个问题,以便它通过“数据集”中的所有记录,并创建新的列表或字典?
You're creating a new dictionary, match_history_data
and then just setting the same entries 'DateCollected'
and 'Orders'
over and over again.您正在创建一个新字典match_history_data
,然后一遍又一遍地设置相同的条目'DateCollected'
和'Orders'
。 Each iteration of your for loop is just overwriting the same entries. for 循环的每次迭代都只是覆盖相同的条目。
What you want is a list of new dictionaries:你想要的是一个新字典列表:
match_history_data = []
for item in dataset:
match_history_data.append(
{"DateCollected" : item["dateCollected"],
"Orders" : item["orders"]})
You can achieve this in a neater fashion using a list comprehension:您可以使用列表推导以更简洁的方式实现此目的:
match_history_data = [{"DateCollected" : item["dateCollected"], "Orders" : item["orders"]} for item in dataset]
How about this这个怎么样
match_history_data = [{"DateCollected":x["dateCollected"], "Orders":x["orders"]} for x in dataset]
What you have right now overwrites a single dictionary as your loop through the original list of dictionaries, since keys are unique in dictionaries.您现在拥有的内容会覆盖单个字典,因为您在原始字典列表中循环,因为键在字典中是唯一的。 What you need to is another list to which you can append the new dictionaries during each iteration to a separate list.您需要的是另一个列表,您可以将每次迭代期间的新词典 append 到一个单独的列表中。
For example例如
new_list = []
for i in dataset:
match_history_data = {}
match_history_data['DateCollected'] = i['dateCollected']
match_history_data['Orders'] = i['orders']
new_list.append(match_history_data)
If you don't want to preserve the original list, you can simply drop the id
key in each dictionary.如果您不想保留原始列表,只需将id
键放在每个字典中即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.