简体   繁体   English

转换列表以在python中自定义字典

[英]convert lists to customize dictionary in python

i want to convert the list data below into a dictionary.how i 我想将下面的列表数据转换为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 : 您可以尝试使用ziplist 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. 如果a是你的密钥,你可以使用value = a + ".jpg"来获取你的价值。 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): 在这种情况下,使用字典理解(Python 2.7和更高版本)初始化它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM