Home > database >  Need to convert list of lists to list of dictionaries or dictionary of dictionaries
Need to convert list of lists to list of dictionaries or dictionary of dictionaries

Time:03-11

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

CodePudding user response:

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'}]

CodePudding user response:

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'}]
  • Related