I have this list of tuples.
List = [('id1', 'name1', 'date1'), ('id1', 'name2', 'date2'), ('id2', 'name3', 'date3'), ('id2', 'name4', 'date4')]
I want to have a function that converts list to become a dictionary such that
Dict = convert('id1', List)
Contents of Dict is {'id1':('name1', 'name2')}
The first parameter filters out the tuples that are of interest based on the first element. It is also the key of the output dictionary. The 2nd element of each tuple will become the values of the output dictionary.
I wrote a little function in Python and it does not work. Thank you very much for your help if you have better suggestions. Forget about my function if it is too far out which I think so. Solving it in a pythonic way is most welcome. I am using Python 2.7
def convertToDict(key, List):
for key in List[0]:
DictOut = {key:[]}
DictOut[key].append(List[0])
You are replacing the DictOut
unconditionally. Instead you should be using setdefault
like this
DictOut.setdefault(key, [])
Your program can be written like this
def convertToDict(my_list):
result_dict = {}
for item in my_list:
result_dict.setdefault(item[0], []).append(item[1])
return result_dict
print convertToDict(my_list)
# {'id2': ['name3', 'name4'], 'id1': ['name1', 'name2']}
If you want to get only the specific keys. you can use this
def convertToDict(key, my_list):
result_dict = {}
for item in my_list:
if item[0] == key:
result_dict.setdefault(item[0], []).append(item[1])
return result_dict
print convertToDict("id1", my_list)
# {'id1': ['name1', 'name2']}
You can actually use collections.defaultdict
for this purpose, like this
from collections import defaultdict
def convertToDict(key, my_list):
result_dict = defaultdict(list)
for item in my_list:
if item[0] == key:
result_dict[item[0]].append(item[1])
return result_dict
print convertToDict("id1", my_list)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments