0

If I have 2 lists:

fruits = ["apple","apple","oranges","watermelon","apple"]
val = ["a","b","c","d","e"]

Each index of val corresponds to the index of fruits

So if I want a dictionary with:

dict
{
"apple" : ["a","b","e"],
"oranges": ["c"],
"watermelon": ["d"]
}

What is the simplest way to achieve this?

Luke B
  • 2,075
  • 2
  • 18
  • 26
candyhunterz
  • 45
  • 1
  • 7

2 Answers2

4

Use a defaultdict with list factory as the output container and iterate over the two lists with zip:

In [162]: out = collections.defaultdict(list)

In [163]: for k, v in zip(fruits, val):
     ...:     out[k].append(v)
     ...:     

In [164]: out
Out[164]: 
defaultdict(list,
            {'apple': ['a', 'b', 'e'], 'oranges': ['c'], 'watermelon': ['d']})

In [165]: dict(out)
Out[165]: {'apple': ['a', 'b', 'e'], 'oranges': ['c'], 'watermelon': ['d']}
heemayl
  • 39,294
  • 7
  • 70
  • 76
0

You can use setdefault to initilize each value with an empty list, then append the values from the other list

fruits = ["apple","apple","oranges","watermelon","apple"]
val = ["a","b","c","d","e"]
d={}

for k, v in zip(fruits, val):
    d.setdefault(k, []).append(v) 

print(d)
# {'apple': ['a', 'b', 'e'], 'oranges': ['c'], 'watermelon': ['d']}
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96