简体   繁体   English

将python列表转换为仅具有键的字典,没有值

[英]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 :) 但是,这不是我需要我的字典使用的格式-感谢您的帮助:)

What you need is a set : 您需要的是一套

A set is an unordered collection of items. 集合是项目的无序集合。 Every element is unique (no duplicates) and must be immutable (which cannot be changed). 每个元素都是唯一的(没有重复项),并且必须是不可变的(不能更改)。

rooms = ["G5a", "G5b", "G11"]
print(set(rooms))

OUTPUT: 输出:

{'G5b', 'G5a', 'G11'}

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.

相关问题 Python将列表转换为具有键值的字典 - Python convert list into Dictionary with key value 如何将列表中的键值对列表转换为python中的字典 - How to convert list of key value pair in list to dictionary in python 将列表变量名称转换为键,并将其值转换为 python 中的字典值 - convert list variable name as key and its value as value of dictionary in python python,按字符而不是键将字典转换为排序列表 - python, convert a dictionary to a sorted list by value instead of key 将标准 python 键值字典列表转换为 pyspark 数据框 - Convert a standard python key value dictionary list to pyspark data frame 如何将数组字典转换为列表并作为 python 中的键值 - how to convert dictionary of array to list and as key value in python 尝试将列表转换为 python 中的字典时出现问题,但它仅从列表中提取最后一个键值对 - Getting issue while trying to convert a list to a dictionary in python but it's extracting only the last key-value pair from the list 如何将具有相同键值的字典的 Python 列表转换为具有值列表的字典 - How to convert a Python list of dictionary with same key value into dictionary with list of values Python-将字典转换为具有列表值的字典 - Python- Convert dictionary to dictionary with list value 如何将具有键值对的列表转换为字典 - How to convert a list with key value pairs to dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM