i want to convert the list data below into a dictionary.how i
['w', 'a', 's', 'x', 'v', 'q']
How to convert it to dictionary with keys but values as list:
{'w':'w.jpg', 'a':'a.jpg', 's':'s.jpg', 'x':'x.jpg', 'v':'v.jpg', 'q':'q.jpg'}
I have a folder of pictures that i want to put them in a dictionary.
>>> l = ['w', 'a', 's', 'x', 'v', 'q']
>>> {e: e+'.jpg' for e in l}
{'w': 'w.jpg', 'a': 'a.jpg', 's': 's.jpg', 'x': 'x.jpg', 'v': 'v.jpg', 'q': 'q.jpg'}
Or
>>> dict(map(lambda x: (x,x+'.jpg'), l))
{'w': 'w.jpg', 'a': 'a.jpg', 's': 's.jpg', 'x': 'x.jpg', 'v': 'v.jpg', 'q': 'q.jpg'}
Or
>>> dict(zip(l,[e+'.jpg' for e in l]))
{'w': 'w.jpg', 'a': 'a.jpg', 's': 's.jpg', 'x': 'x.jpg', 'v': 'v.jpg', 'q': 'q.jpg'}
You can try using zip
and list comprehension
:
my_images = dict(zip(names,[i+'.jpg' for i in names]))
Output:
{'w': 'w.jpg', 'a': 'a.jpg', 's': 's.jpg', 'x': 'x.jpg', 'v': 'v.jpg', 'q': 'q.jpg'}
if a
is your key, you could just use value = a + ".jpg"
to get your value. Creating a dictionary for that isn't very useful.
What would be useful would be to create the dictionary and update it later if you need it. In that case, initialize it with a dictionary comprehension (Python 2.7 and higher):
dct = {a:a+".jpg" for a in ['w', 'a', 's', 'x', 'v', 'q']}
This dictionary doesn't bring anything new since values can be deduced from keys with a simple addition.
then to change a value to handle special cases:
dct['w'] = "new_w.jpg"
now the dictionary is useful if you need to handle cases like that. Otherwise avoid it.
lst = ['w', 'a', 's', 'x', 'v', 'q']
images = {key:key+".jpg" for key in lst}
Output:
{'a': 'a.jpg',
'q': 'q.jpg',
's': 's.jpg',
'v': 'v.jpg',
'w': 'w.jpg',
'x': 'x.jpg'}
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.