简体   繁体   中英

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:

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:

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:

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.

 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:

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:

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)

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