[英]keys with multiple values in a dictionary (Python)
I have the following list (I have omitted some values from the list): 我有以下列表(我已从列表中省略了一些值):
all_examples= ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5',...]
I need to create a dictionary such that a key has multiple values. 我需要创建一个字典,以便键具有多个值。
dict = {"A":[1,1], "B":[2,1]}
I looked for some possible solution, but couldn't make it work on mine. 我找了一些可能的解决方案,但无法让它在我的工作。
for python3 you can use a dict comp, using extended iterable unpacking splitting each string in your list and creating a key/value paring from the split elements: 对于python3,您可以使用dict comp,使用扩展的可迭代解包来拆分列表中的每个字符串并创建从拆分元素中删除的键/值:
l = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']
d = {k: list(map(int,rest)) for k,*rest in (s.split(",") for s in l) }
For python2 the syntax is not quite as nice: 对于python2,语法不太好:
l = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']
d = {s[0]: map(int, s[1:] ) for s in (s.split(",") for s in l)}
Both should give you something like: 两者都应该给你这样的东西:
In [32]: d = {k: list(map(int,rest)) for k,*rest in (s.split(",") for s in l) }
In [33]: d
Out[33]: {'A': [1, 1], 'B': [2, 1], 'C': [4, 4], 'D': [4, 5]}
To break it down, the inner gen exp is creating our split strings: 为了打破它,内部的exp创建我们的分裂字符串:
In [35]: list (s.split(",") for s in l)
Out[35]: [['A', '1', '1'], ['B', '2', '1'], ['C', '4', '4'], ['D', '4', '5']]
Then in the python3 case in for k,*rest in..
k
is the first element of the lists, the *rest
syntax basically means everything else. 然后在python3的情况下,
for k,*rest in..
k
是列表的第一个元素, *rest
语法基本上意味着其他一切。
In [37]: for k,*rest in (s.split(",") for s in l):
print(k, rest)
....:
A ['1', '1']
B ['2', '1']
C ['4', '4']
D ['4', '5']
So putting it all together to create the dict using a for loop would be: 所以将它们放在一起使用for循环创建dict将是:
In [38]: d = {}
In [39]: for k,*rest in (s.split(",") for s in l):
d[k] = list(map(int, rest))
....:
In [40]: d
Out[40]: {'A': [1, 1], 'B': [2, 1], 'C': [4, 4], 'D': [4, 5]}
Or in the case of python2: 或者在python2的情况下:
In [42]: d = {}
In [43]: for spl in (s.split(",") for s in l):
d[spl[0]] = list(map(int,spl[1:]))
....:
In [44]: d
Out[44]: {'A': [1, 1], 'B': [2, 1], 'C': [4, 4], 'D': [4, 5]}
A simple & straight-forward solution: 一个简单而直接的解决方案:
result = {}
for l in all_examples:
split_list = l.split(',')
result[split_list[0]] = [int(val) for val in split_list[1:]]
A short but not so efficient solution, 一个简短但不那么有效的解决方案,
all_examples = ['A,1,1', 'B,2,1', 'C,4,4', 'D,4,5']
d = dict((a.split(',')[0], a.split(',')[1:])for a in all_examples)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.