T
T
tekleworm2018-04-20 11:46:05
Python
tekleworm, 2018-04-20 11:46:05

How to merge two lists into a dictionary?

There are two lists, for example list 1:

'6.95',
 '6.95',
 '6.95',
 '6.95',
 '6.96',
 '6.96',
 '6.96',
 '6.96',
 '6.96',
 '6.96',
 '6.96',
 '6.96',
 '6.96',
 '6.96',
 '6.96',
 '6.96',

and list 2:
'0/4',
 '0/10',
 '0/6',
 '0/18',
 '0/9',
 '0/24',
 '0/22',
 '0/11',
 '0/14',
 '0/7',

The number of elements is the same. But in list one, the elements are repeated, and when I do dict[str(list1)] = str(list2)
that when the element from list 1 is repeated, the value is overwritten. How to do so, to get such a structure.
'6.95':  '0/4', '0/10', '0/6', '0/18','0/9','0/24'
 '6.96'; '0/22','0/11', '0/14','0/7',

or
'6.95': '0/4',
'6.95':  '0/10',
'6.95':  '0/18'
 '6.96':  '0/22',
 '6.96': '0/11'
и тд

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-04-20
@tekleworm

A variant for the case when for non-repeating keys the values ​​do not need to be wrapped in a list:

d = {}
for k, v in zip(list1, list2):
    if k in d:
        if not isinstance(d[k], list):
            d[k], t = [], d[k]
            d[k].append(t)
        d[k].append(v)
    else:
        d[k] = v

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question