Create dictionary python with keys

I'd like to get from this:

keys = [1,2,3]

to this:

{1: None, 2: None, 3: None}

Is there a pythonic way of doing it?

This is an ugly way to do it:

>>> keys = [1,2,3]
>>> dict[[[1,2]]]
{1: 2}
>>> dict[zip[keys, [None]*len[keys]]]
{1: None, 2: None, 3: None}

evtoh

4343 gold badges8 silver badges21 bronze badges

asked Feb 11, 2010 at 2:43

Juanjo ContiJuanjo Conti

27.7k39 gold badges106 silver badges131 bronze badges

1

dict.fromkeys directly solves the problem:

>>> dict.fromkeys[[1, 2, 3, 4]]
{1: None, 2: None, 3: None, 4: None}

This is actually a classmethod, so it works for dict-subclasses [like collections.defaultdict] as well.

The optional second argument, which defaults to None, specifies the value to use for the keys. Note that the same object will be used for each key, which can cause problems with mutable values:

>>> x = dict.fromkeys[[1, 2, 3, 4], []]
>>> x[1].append['test']
>>> x
{1: ['test'], 2: ['test'], 3: ['test'], 4: ['test']}

answered Feb 11, 2010 at 2:45

Thomas WoutersThomas Wouters

127k23 gold badges146 silver badges122 bronze badges

2

Use a dict comprehension:

>>> keys = [1,2,3,5,6,7]
>>> {key: None for key in keys}
{1: None, 2: None, 3: None, 5: None, 6: None, 7: None}

The value expression is evaluated each time, so this can be used to create a dict with separate lists [say] as values:

>>> x = {key: [] for key in [1, 2, 3, 4]}
>>> x[1] = 'test'
>>> x
{1: 'test', 2: [], 3: [], 4: []}

answered Feb 11, 2010 at 11:18

Adrien PlissonAdrien Plisson

21.5k4 gold badges40 silver badges73 bronze badges

7

dict.fromkeys[keys, None]

answered Feb 11, 2010 at 2:48

Dominic CooneyDominic Cooney

6,1181 gold badge25 silver badges38 bronze badges

4

A list comprehension can be used to build a list of key-value pairs, which can then be passed to the dict constructor. Thus:

>>> keys = {"a", "b", "c", "d"}
>>> d = dict[[[key, []] for key in keys]]
>>> d
{'d': [], 'c': [], 'a': [], 'b': []}

The value expression is evaluated each time, creating separate lists in the above example:

>>> d['a'].append['test']
>>> d
{'d': [], 'c': [], 'a': ['test'], 'b': []}

answered Aug 24, 2015 at 12:31

3

Simply iterate and add the values to an empty dictionary:

d = {}
for i in keys:
    d[i] = None

answered Feb 11, 2010 at 4:59

inspectorG4dgetinspectorG4dget

106k25 gold badges137 silver badges235 bronze badges

0

In many workflows where you want to attach a default / initial value for arbitrary keys, you don't need to hash each key individually ahead of time. You can use collections.defaultdict. For example:

from collections import defaultdict

d = defaultdict[lambda: None]

print[d[1]]  # None
print[d[2]]  # None
print[d[3]]  # None

This is more efficient, it saves having to hash all your keys at instantiation. Moreover, defaultdict is a subclass of dict, so there's usually no need to convert back to a regular dictionary.

For workflows where you require controls on permissible keys, you can use dict.fromkeys as per the accepted answer:

d = dict.fromkeys[[1, 2, 3, 4]]

answered Dec 17, 2018 at 11:47

jppjpp

152k32 gold badges256 silver badges319 bronze badges

Just because it's fun how the dict constructor works nicely with zip, you can repeat the default value and zip it to the keys:

from itertools import repeat

keys = [1, 2, 3]
default_value = None

d = dict[zip[keys, repeat[default_value]]]
print[d]

Will give:

{1: None, 2: None, 3: None}

repeat creates an infinite iterator of the element passed to it but as zip stops on the shortest iterable all works well.

answered Mar 9 at 8:45

TomerikooTomerikoo

16.6k15 gold badges38 silver badges54 bronze badges

Can you add keys to a dictionary Python?

You can add key to dictionary in python using mydict["newkey"] = "newValue" method. Dictionaries are changeable, ordered, and don't allow duplicate keys. However, different keys can have the same value.

How do you initialize a dictionary using only the keys?

Let's see the different methods we can do this task..
Method #1 : By iterating through list..
Method #2 : Using dictionary comprehension..
Method #3 : Using zip[] function..
Method #4 : Using fromkeys[] method..

How do you create a dictionary using key

Below are the two approaches which we can use..
Assigning a new key as subscript. We add a new element to the dictionary by using a new key as a subscript and assigning it a value. ... .
Using the update[] method. ... .
By merging two dictionaries..

How do you create a Python dictionary?

How to Create a Dictionary in Python. A dictionary in Python is made up of key-value pairs. In the two sections that follow you will see two ways of creating a dictionary. The first way is by using a set of curly braces, {} , and the second way is by using the built-in dict[] function.

Chủ Đề