0

I'm new to Python. I'm trying to zip 2 lists into a dictionary without losing the values of the duplicated keys and keep values as a list in the dictionary.

Example:

list1 = [0.43, -1.2, 50, -60.5, 50]

list2 = ['tree', 'cat', 'cat', 'tree', 'hat']

I'm trying to get the following outcome:

{'tree': [0.43, -60.5],'cat': [-1.2, 50],'hat': [50]}

Thanks for your help.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161

3 Answers3

2

You can use the setdefault method of the dictionary:

list1 = [0.43, -1.2, 50, -60.5, 50]
list2 = ['tree', 'cat', 'cat', 'tree', 'hat']
d = {}
for k, v in zip(list2, list1):
    d.setdefault(k, []).append(v)

Results:

>>> d
{'cat': [-1.2, 50], 'hat': [50], 'tree': [0.43, -60.5]}
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • 1
    How is this useful? It solves the problem as set but without a MVP we don't know what problems the OP actually had, if it was a homework question then they have an answer but it cheats them of a chance to learn.. – Noelkd Mar 21 '16 at 19:03
  • 3
    This answer looks perfectly OK, and produces the desired outcome. I wonder why @Noelkd thinks the question is unclear. – Jan Christoph Terasa Mar 21 '16 at 19:05
  • 1
    [Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it.](http://stackoverflow.com/help/on-topic) – Noelkd Mar 21 '16 at 19:07
  • @Noelkd Well, the OP can learn how to solve this kind of problem using just one dictionary method. – Mike Müller Mar 21 '16 at 19:07
2

The answer provided by Mike Muller works perfectly well. An alternative, perhaps slightly more pythonic way would be to use defaultdict from the collections library:

from collections import defaultdict

list1 = [0.43, -1.2, 50, -60.5, 50]
list2 = ['tree', 'cat', 'cat', 'tree', 'hat']
d = defaultdict(list)
for k, v in zip(list2, list1):
    d[k].append(v)
T. Silver
  • 372
  • 1
  • 6
0

just for completeness, this is how I would have do it in my early days programing

>>> list1 = [0.43, -1.2, 50, -60.5, 50]
>>> list2 = ['tree', 'cat', 'cat', 'tree', 'hat']
>>> result=dict()
>>> for k,v in zip(list2,list1):
        if k in result:
            result[k].append(v)
        else:
            result[k]=[v]


>>> result
{'hat': [50], 'tree': [0.43, -60.5], 'cat': [-1.2, 50]}
>>> 
Copperfield
  • 8,131
  • 3
  • 23
  • 29