[英]convert python list into dictionary with key only , no value
I have a list of room names in python, however I need it to be a dictionary, simply in the form {"room1", "room2", "room3"}
我用python列出了房间名称,但是我需要将它作为字典,形式为
{"room1", "room2", "room3"}
Currently, my code can take the list and turn to a dictionary with both values and keys, ie {"room1":0, "room2":1, "room3": 2}
etc. 目前,我的代码可以获取列表并转到包含值和键的字典,例如
{"room1":0, "room2":1, "room3": 2}
等。
my code is as follows: 我的代码如下:
rooms = ["G5a", "G5b", "G11"]
roomdict = dict(zip(rooms,range(len(rooms))))
print(roomdict)
But, this is not the format I need my dictionary to be in - thanks for your help in advanace :) 但是,这不是我需要我的字典使用的格式-感谢您的帮助:)
On the odd chance that your really need a dict with keys and empty values: 如果您确实需要一个包含键和空值的dict,这很奇怪:
mydict = {"room1" : None, "room2": None, "room3" : None}
You could use the dict.fromkeys()
method: 您可以使用
dict.fromkeys()
方法:
rooms = ["G5a", "G5b", "G11"]
roomdict = dict.fromkeys(rooms, None)
print(roomdict)
Output: 输出:
{'G5b': None, 'G11': None, 'G5a': None}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.