I need to make a dictionnary 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 dictionnary: d = {"a", "b", "c"} ?
Dictionaries in Python Almost any type of value can be used as a dictionary key in Python. You can even use built-in objects like types and functions. However, there are a couple restrictions that dictionary keys must abide by. First, a given key can appear in a dictionary only once.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
To create an empty dictionary, first create a variable name which will be the name of the dictionary. Then, assign the variable to an empty set of curly braces, {} . Another way of creating an empty dictionary is to use the dict() function without passing any arguments.
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'])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With