Reputation: 99428
How can we convert a dict with tuples (key, value), into a list of dicts, each dict with keys "key" and "value"?
For example:
dic={'Tim':3, 'Kate':2}
becomes
lst = [{'Name':'Tim', 'Age':3}, {'Name':'Kate', 'Age':2}]
Upvotes: 1
Views: 659
Reputation: 10223
Dictionary to list of dictionary
>>> dic={'Tim':3, 'Kate':2}
>>> [{"Name":i, "Age":j} for i,j in dic.items()]
[{'Age': 3, 'Name': 'Tim'}, {'Age': 2, 'Name': 'Kate'}]
>>>
Best to use Dictionary Data Structure because Time Complexity to Find Key is O(1)
Constant Time i.e. it is not depend on the size of dictionary
Demo to find age of Kate.
Need to Iterate every element from the List. Time Complexity is from O(1) to O(N)
>>> info
[{'Age': 3, 'Name': 'Tim'}, {'Age': 2, 'Name': 'Kate'}]
>>> age = -1
>>> find_name = "Kate"
>>> for i in info:
... if i["Name"]==find_name:
... age = i["Age"]
... break
...
>>> age
2
>>>
By dictionary: Time Complexity is O(1)
>>> dic = {'Tim':3, 'Kate':2}
>>> find_name = "Kate"
>>> if find_name in dic:
... age = dic[find_name]
... else:
... age = -1
... print "No data for %s name"%find_name
...
>>> age
2
>>>
Upvotes: 4
Reputation: 107297
You can use a list comprehension :
>>> dic={'Tim':3, 'Kate':2}
>>> [{'Name':i, 'Age':j} for i,j in dic.items()]
[{'Age': 3, 'Name': 'Tim'}, {'Age': 2, 'Name': 'Kate'}]
and for opposite :
>>> l=[{'Name':i, 'Age':j} for i,j in dic.items()]
>>> dict((i.values()[::-1] for i in l))
{'Tim': 3, 'Kate': 2}
Upvotes: 5
Reputation: 52101
Another way using map
>>> dic={'Tim':3, 'Kate':2}
>>> map(lambda x: x,dic)
['Tim', 'Kate']
>>> map(lambda x:{'Age':dic[x],'Name':x},dic)
[{'Age': 3, 'Name': 'Tim'}, {'Age': 2, 'Name': 'Kate'}]
>>>
Note - map
is slower compared to a list comprehension, but I have just added it as an alternative
Upvotes: 3