[英]Python: How to iterate over a list of dictionaries and add each dictionary as value to a new dictionary with a unique key - no repeats
Have a list of dicts. 列出字典。 I want to add a key to each dict and append them all to one dict.
我想向每个字典添加密钥,并将它们全部附加到一个字典。 How do i do this without getting repeats of the same entry into new dict?
我该如何做而又不会重复输入相同的新字典?
I tried this code: 我尝试了这段代码:
# a_list is a list of dictionaries
# category_name is a string
def make_dict(a_list, category_name=None):
a_dict = {}
for item in a_list:
for i in range(0, len(a_list)):
a_dict.setdefault(category_name + str(i+1), item)
return a_dict
But while it creates a new name, the first object in the list is repeated for the total number of objects in the list. 但是,当它创建一个新名称时,列表中的第一个对象将重复该列表中的对象总数。
{
"Open Port 1": {
"LocalAddress": "::",
"LocalPort": 58448,
"RemoteAddress": "::",
"RemotePort": 0,
"State": 100
},
"Open Port 2": {
"LocalAddress": "::",
"LocalPort": 58448,
"RemoteAddress": "::",
"RemotePort": 0,
"State": 100
},
"Open Port 3": {
"LocalAddress": "::",
"LocalPort": 58448,
"RemoteAddress": "::",
"RemotePort": 0,
"State": 100
}, ... etc
Any ideas of how to solve this issue? 关于如何解决此问题的任何想法?
With the code you posted - you'll get the same key "Open Port 1"
reassigned with each next dict cause the counter i
is not incremented: 使用您发布的代码-您将获得与每个下一个字典重新分配的相同密钥
"Open Port 1"
,因为计数器i
不会增加:
i = 0
for item in a_list:
a_dict.setdefault(category_name + str(i+1), item)
return a_dict
The corrected way would be: 正确的方法是:
i = 0
for item in a_list:
a_dict.setdefault(category_name + str(i+1), item)
i += 1
return a_dict
But , in your simple case you may just go with dict comprehension: 但是 ,在您的简单情况下,您可以仅使用dict理解:
a_dict = {category_name + str(i): d for i, d in enumerate(a_list, 1)}
Yeah got it fixed straight away. 是的,马上就解决了。
for item in a_list:
a_dict[(category_name + str(i))] = item
i += 1
return a_dict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.