简体   繁体   中英

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]}

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.

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)
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM