如何在python中从列表加载dict?

2024-09-28 03:21:24 发布

您现在位置:Python中文网/ 问答频道 /正文

有这样的格言:

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

列表如下:

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

如何将列表中的所有“a”作为列表放入mydict['a']中。你知道吗

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

Tags: log列表mydict格言ndict
3条回答
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.')

斯文·马纳奇的答案更聪明更好,但这就是我提出的版本。我能看出我的解决办法的局限性。你知道吗

这是一个标准问题集合.defaultdict解决:

from collections import defaultdict

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

遍历列表,并将每个值附加到正确的键:

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

我将dict重命名为my_dict,以避免隐藏内置类型。你知道吗

相关问题 更多 >

    热门问题