Reputation: 1103
How do we change a list into a dictionary?
for example we want to make the list l=["cat","dog","elephant","chicken","lion"]
into {"cat":0, "dog":1,"elephan":2, "chicken":3, "lion":4}
I think I can get a dictionary with all values equals to 0 by dict.fromkeys(l, 0)
. But I need a dictionary with distinct values
Upvotes: 0
Views: 80
Reputation: 630
You could try the below code:
import random
l=["cat","dog","elephant","chicken","lion"] # keys
value = random.sample(range(1, 100), len(l)) # values
my_dict = list(zip(l,value))
my_dict = dict(my_dict)
print(my_dict)
Upvotes: 1
Reputation: 21
If the intention is to get the frequency of the words, you can use Counter from collections. The fromkeys method of dict doesn't accept callable as value for it's second argument, you can use dict comprehension without any limits otherwise!
>>> from collections import Counter
>>> l=["cat","dog","elephant","chicken","lion"]
>>> d=Counter(l)
>>> d
Counter({'cat': 1, 'dog': 1, 'elephant': 1, 'chicken': 1, 'lion': 1})
Upvotes: 1