[英]Python - How to create a dictionary list from another list which having two keys with multiple values?
I am trying to create a dictionary list from another list which has two keys with multiple values as follows:我正在尝试从另一个列表创建一个字典列表,该列表具有两个具有多个值的键,如下所示:
contact_items = [{'type': ['value1', 'value2', 'value3'],
'name': ['john', 'SCANIA', 'MARK']}]
list1 = ''
list2 = ''
list3 = []
test_dict = {}
for item in contact_items:
list1 = item['type']
list2 = item['name']
test_dict = {}
for k in list1:
for l in list2:
test_dict['type'] = k
test_dict['name'] = l
list3.append(test_dict)
print(list3)
The above code is not returning the dictionary list as expected.上面的代码没有按预期返回字典列表。
Outputs:输出:
[{'type': 'value3', 'name': 'MARK'}, {'type': 'value3', 'name': 'MARK'}, {'type': 'value3', 'name': 'MARK'}, {'type': 'value3', 'nam
e': 'MARK'}, {'type': 'value3', 'name': 'MARK'}, {'type': 'value3', 'name': 'MARK'}, {'type': 'value3', 'name': 'MARK'}, {'type': 'v
alue3', 'name': 'MARK'}, {'type': 'value3', 'name': 'MARK'}]
Expected:预期的:
result=[{'type':'value1','name':'john'},
{'type':'value2','name':'SCANIA'},
{'type':'value3','name':'MARK'}]
You're putting the same dict in the list multiple times.您多次将相同的字典放入列表中。 And you're assigning different values to the same variables in your first loop.
而且您在第一个循环中为相同的变量分配了不同的值。 And you're iterating through every combination of items in
list1
and list2
in your nested loop.而且您正在迭代嵌套循环中
list1
和list2
中的每个项目组合。
Here is a way to get the outcome you specified from the input you specified:这是一种从您指定的输入中获取您指定的结果的方法:
types = contact_items[0]['type']
names = contact_items[0]['name']
list3 = [{'type': t, 'name': n} for (t,n) in zip(types, names)]
See list comprehensions , zip .见列表推导, zip 。
This is very trivial.这是非常微不足道的。 Look up list comprehension and dictionary comprehension.
查找列表理解和字典理解。
result = [{"type": contact_items[0]["type"][i],
"name": contact_items[0]["name"][i]}
for i in range(len(contact_items[0]["name"])) ]
Neater.更整洁。
items = contact_items[0]
result = [{"type": items["type"][i], "name": items["name"][i]} for i in range(len(items["name"]))]
result
You can use list comprehension in combination with zip
to achieve this.您可以将列表理解与
zip
结合使用来实现此目的。
result = [
{"name": name, "type": type}
for type, name in zip(*contact_items[0].values())
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.