简体   繁体   中英

Need to convert list of lists to list of dictionaries or dictionary of dictionaries

I need to convert this list of lists into list of dictionaries or dictionary of dictionaries because I need the key and value of each list. And when I convert the whole thing into a dictionary, it counts 'protocol adapter' as 1 key instead of 2, but i need both elements

Input:

li = [['calculator', '2.4'], ['data_feed', '3.2'], ['protocol_adapter', '1.0'], ['protocol_adapter', '1.1'], ['local_network_connector', '3.4'], ['data_feed', '3.2.1'], ['calculator', '2.4.1'], ['protocol_adapter', '1.2']]

into:

[{'calculator': '2.4'}, {'data_feed': '3.2'}, {'protocol_adapter': '1.0'}, {'protocol_adapter': '1.1'}, {'local_network_connector': '3.4'}]

I tried something like

d = []
for x in li:
    new = dict(x)
    d.append(new)

But it gives an error

A combined list/dictionary comprehension should do the trick:

li = [['calculator', '2.4'], ['data_feed', '3.2'], ['protocol_adapter', '1.0'], ['protocol_adapter', '1.1'], ['local_network_connector', '3.4'], ['data_feed', '3.2.1'], ['calculator', '2.4.1'], ['protocol_adapter', '1.2']]

d = [{k: v} for k, v in li]

print(d)

Output:

[{'calculator': '2.4'}, {'data_feed': '3.2'}, {'protocol_adapter': '1.0'}, {'protocol_adapter': '1.1'}, {'local_network_connector': '3.4'}, {'data_feed': '3.2.1'}, {'calculator': '2.4.1'}, {'protocol_adapter': '1.2'}]

Try this:

d = []
for key, value in li:  # Extract the 2 elements from the list
    new = {key: value}
    d.append(new)
print(d)

# [{'calculator': '2.4'}, {'data_feed': '3.2'}, {'protocol_adapter': '1.0'}, {'protocol_adapter': '1.1'}, {'local_network_connector': '3.4'}, {'data_feed': '3.2.1'}, {'calculator': '2.4.1'}, {'protocol_adapter': '1.2'}]

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