Luke Livingstone
Luke Livingstone

Reputation: 129

List to Dictionary - Python

I have the following list:

[{'ext': '193', 'value': 'Name1'},
 {'ext': '194', 'value': 'Name 2'},
 {'ext': '192', 'value': 'Name3'},
 {'ext': '195', 'value': 'Name4'}]

How to create a dictionary of this to look like the following:

{'193': 'Name1', '194': 'Name 2'} 

etc.

Upvotes: 0

Views: 156

Answers (3)

Aashutosh jha
Aashutosh jha

Reputation: 618

Since list has collection of tuple, You can achieve the same in below way:

mappings
[{'ext': '193', 'value': 'Name1'}, {'ext': '194', 'value': 'Name 2'}, 
{'ext': '192', 'value': 'Name3'}, {'ext': '195', 'value': 'Name4'}]
dict={}
for i in mappings:
    dict[i["ext"]] = i["value"]

dict
{'195': 'Name4', '194': 'Name 2', '193': 'Name1', '192': 'Name3'}

Upvotes: 0

falsetru
falsetru

Reputation: 369094

Using dictionary comprehension:

mappings = [
    {'ext': '193', 'value': 'Name1'},
    {'ext': '194', 'value': 'Name 2'},
    {'ext': '192', 'value': 'Name3'},
    {'ext': '195', 'value': 'Name4'},
]

{d['ext']: d['value'] for d in mappings}
# => {'195': 'Name4', '194': 'Name 2', '193': 'Name1', '192': 'Name3'}

Upvotes: 5

user1907906
user1907906

Reputation:

Build a list of tuples and convert them to a dict:

l = [{'ext': '193', 'value': 'Name1'},
     {'ext': '194', 'value': 'Name 2'},
     {'ext': '192', 'value': 'Name3'},
     {'ext': '195', 'value': 'Name4'}]
d = dict((i["ext"], i["value"]) for i in l)
print(d)

Output:

{'193': 'Name1', '194': 'Name 2', '195': 'Name4', '192': 'Name3'}

Upvotes: 2

Related Questions