How do I load a dict from a list in python?

Have to dictate:

mydict= {'a':[],'b':[],'c':[],'d':[]}

      

list:

log = [['a',917],['b', 312],['c',303],['d',212],['a',215],['b',212].['c',213],['d',202]]

      

How can I get all 'a' from a list in mydict ['a'] as a list.

ndict= {'a':[917,215],'b':[312,212],'c':[303,213],'d':[212,202]}

      

+3


source to share


3 answers


Go through the list and add each value to the correct key:

for key, value in log:
    my_dict[key].append(value)

      



I renamed dict

to my_dict

to avoid built-in type shading.

+7


source


This is the standard problem collect.defaultdict solves:



from collections import defaultdict

mydict = defaultdict(list)
for key, value in log:
    mydict[key].append(value)

      

+4


source


myDict = {}
myLog = [['a', 917], ['b', 312], ['c', 303],['d', 212], ['a', 215],
         ['b', 212], ['c', 213], ['d', 202]]

# For each of the log in your input log
for log in myLog:
    # If it is already exist, you append it
    if log[0] in myDict:
        myDict[log[0]].append(log[1])
    # Otherwise you can create a new one
    else:
        myDict[log[0]] = [log[1]]

# Simple test to show it works
while True:
    lookup = input('Enter your key: ')
    if lookup in myDict:
        print(myDict[lookup])
    else:
        print('Item not found.')

      

Sven Marnach's answer is smarter and better, but this version I am coming. I see the limitation of my solution.

+2


source







All Articles