简体   繁体   中英

change a list into a dictionary with random values

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

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})

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)

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