Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Dictionary with only keys?

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"} ?
like image 420
MartinM Avatar asked Feb 20 '17 12:02

MartinM


People also ask

Can you make a dictionary with only keys in Python?

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.

Can a dictionary have only keys?

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.

How do you create an empty dictionary key?

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.


2 Answers

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'])
like image 136
khelwood Avatar answered Oct 10 '22 06:10

khelwood


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.

like image 45
Ma0 Avatar answered Oct 10 '22 06:10

Ma0