18

I need to make a dictionary containing only keys.

I cannot use d.append() as it is not a list, neither setdefault as it needs 2 arguments: a key and a value.

It should work as the following:

d = {}

add "a":

d = {"a"}

add "b":

d = {"a", "b"}

add "c"...

# Final result is:

d = {"a", "b", "c"}

What is the code I need to get this result? Or is it another solution? Such as making a list.

l = ["a", "b", "c"] # and transform it into a dictionary: d = {"a", "b", "c"} ?
MartinM
  • 191
  • 1
  • 1
  • 6

3 Answers3

25

A dict with only keys is called a set.

Start with an empty set instead of a dictionary.

d = set()
d.add('a')
d.add('b')
d.add('c')

You can also create a set via a {} expression:

d = { 'a', 'b', 'c' }

Or using a list:

d = set(['a', 'b', 'c'])
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • and how I retrive value b? in a dictionary I don't need to iterate over it – Leonardo Rick Sep 25 '20 at 18:54
  • @LeonardoRick You can get the elements of a set by iterating it. In a dict if you already have a key you can look up the associated value, but in a set there is no value. So if you already have the key, there is nothing to look up. Or what are you asking? – khelwood Sep 25 '20 at 18:56
  • I already have the key, but wan't to check if this key is in the set. In a dict It will be fast as `if 'key' in dict`. Can I do that on a set? What's de difference of doing this on a set, dict or even a list – Leonardo Rick Sep 25 '20 at 19:23
  • 1
    @LeonardoRick Yes `if key in myset` is as fast as `if key in mydict`. Much faster than in a list. See [docs for set](https://docs.python.org/3/library/stdtypes.html#set) – khelwood Sep 25 '20 at 19:25
  • Important note: `set` will not preserve the insertion order. `print(d)` will print `{'b', 'c', 'a'}` (not {'a', 'b', 'c',}) – jerrymouse Sep 25 '21 at 19:32
9

That should do it:

l = ["a", "b", "c"]

d = {k:None for k in l}

As @Rahul says in the comments, d = {"a", "b", "c"} is not a valid dictionary definition since it is lacking the values. You need to have values assigned to keys for a dictionary to exist and if you are lacking the values you can just assign None and update it later.

Ma0
  • 15,057
  • 4
  • 35
  • 65
6

You need a set not a dictionary,

l = ["a", "b", "c"]
d = set(l)
Rahul K P
  • 15,740
  • 4
  • 35
  • 52