Merlin
Merlin

Reputation: 25639

How load a dict from a list in python?

Have dict like:

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

list like:

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

How do i get all 'a' from list into mydict['a'] as a list.

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

Upvotes: 3

Views: 198

Answers (3)

George
George

Reputation: 4674

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 that's the version I come up. I can see the limitation of my solution.

Upvotes: 2

joaquin
joaquin

Reputation: 85603

This is a standard problem that collections.defaultdict solves:

from collections import defaultdict

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

Upvotes: 4

Sven Marnach
Sven Marnach

Reputation: 601779

Iterate over the list, and append each value to the correct key:

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

I renamed dict to my_dict to avoid shadowing the built-in type.

Upvotes: 7

Related Questions