0

I have a list of room names in python, however I need it to be a dictionary, simply in the form {"room1", "room2", "room3"}

Currently, my code can take the list and turn to a dictionary with both values and keys, i.e. {"room1":0, "room2":1, "room3": 2} etc.

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

DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • 4
    You mean a `set`? – meowgoesthedog Jan 31 '19 at 09:51
  • Thats not a `dict` behaviour – DirtyBit Jan 31 '19 at 09:51
  • There is no such thing as a dictionary with no values. `{a, b, c}` is a set. Which is a different type of structure. You could perhaps use a dictionary where all values are just set to None? – Vincent Jan 31 '19 at 09:52
  • yeah sure - not sure what its called - just need it to be name = {"room1", "room2", "room3"} etc. – Natasha Bayliss Jan 31 '19 at 09:53
  • Possible duplicate of [How to construct a set out of list items in python?](https://stackoverflow.com/questions/15768757/how-to-construct-a-set-out-of-list-items-in-python) – Georgy Jan 31 '19 at 10:04
  • Although of course the keys of a dictionary are a set, a Python dictionary's keys also maintain their insertion order. So in situations where you want to maintain the order of the keys, this is the right question to ask. – Josiah Yoder Jun 14 '23 at 16:33
  • This is NOT a duplicate of "How to construct a set ...", because constructing a dictionary with just keys is a distinct and worthwhile goal, as I argued in my previous comment. – Josiah Yoder Jun 14 '23 at 16:34

2 Answers2

2

On the odd chance that your really need a dict with keys and empty values:

mydict = {"room1" : None, "room2": None, "room3" : None}

You could use the dict.fromkeys() method:

rooms = ["G5a", "G5b", "G11"]
roomdict = dict.fromkeys(rooms, None)

print(roomdict)

Output:

{'G5b': None, 'G11': None, 'G5a': None}
Powertieke
  • 2,368
  • 1
  • 14
  • 21
1

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'}
DirtyBit
  • 16,613
  • 4
  • 34
  • 55