[英]Append new values to the same key in a Python dictionary
我正在输入:
5
A 3
A 2
A 4
B 13
B 14
我想像这样把它们放在字典里。
{A: ['3', '2', '4'] , B['13','14']}
但我得到了这个:
{'A': ['3', '2', '4'], 'B': ['1', '3', '14']}
我试过:
N = int(input())
d = dict()
for i in range(N):
first,second = [j for j in input().split()]
if first in d:
d[first].append(second)
else:
d[first] = list(second)
print(d)
你要
d[first] = [second]
不是
d[first] = list(second)
list(string)
遍历string
并将每个单独的字符作为单独的元素放置在列表中。
[string]
创建一个以整个string
为元素的列表。
在输入之后,它会检查它是否已经在字典中,如果它附加了新值,如果它不存在,那么它会在字典中创建一个新列表。
N = int(input())
d = dict()
for i in range(N):
i = input()
lst = i.split()
if lst[0] in d:
d[lst[0]].append(lst[1])
else:
d[lst[0]] = [lst[1]]
print(d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.