简体   繁体   中英

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.

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 .

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.

result = [
    {"name": name, "type": type}
    for type, name in zip(*contact_items[0].values())
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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