This short article teaches you 3 ways of creating a Python dictionary.
Here are 3 ways in which you can create a Python π dictionary: (Of the three, the last one is the least commonly used.)
>>> dict([(1, "one"), (2, "two")])
{1: 'one', 2: 'two'}
>>> dict(name="Rodrigo", twitter="mathsppblog")
{'name': 'Rodrigo', 'twitter': 'mathsppblog'}
>>> dict.fromkeys(["likes", "retweets"], 0)
{'likes': 0, 'retweets': 0}
The built-in dict
can take an iterable with key, value pairs.
Useful, for example, when you have a bunch of keys and a bunch of values that you put together with zip
:
>>> dict([(1, "one"), (2, "two")])
{1: 'one', 2: 'two'}
>>> keys = range(1, 4)
>>> values = "one two three".split()
>>> dict(zip(keys, values))
{1: 'one', 2: 'two', 3: 'three'}
In this particular case, you could also get creating with enumerate
and make use of the keyword argument start
:
>>> dict(enumerate(values, start=1))
{1: 'one', 2: 'two', 3: 'three'}
You can use keyword arguments in dict
to define key, value pairs in your dictionary!
However, this only works if your keys are valid variable names:
# Values don't have to be strings:
>>> dict(one=1, two=2)
{'one': 1, 'two': 2}
# But the keys have to:
>>> dict(1="one", 2="two")
File "<stdin>", line 1
dict(1="one", 2="two")
^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
# Keys have to be valid variable names:
>>> dict(name="Rodrigo", twitter="mathsppblog")
{'name': 'Rodrigo', 'twitter': 'mathsppblog'}
dict.fromkeys
The class method dict.fromkeys
accepts an iterable and a value, and produces a dictionary where all keys have that value.
By default, that value is None
:
# Default value is None:
>>> dict.fromkeys("abc")
{'a': None, 'b': None, 'c': None}
>>> dict.fromkeys(range(5))
{0: None, 1: None, 2: None, 3: None, 4: None}
# Different default values:
>>> dict.fromkeys(range(5), ";)")
{0: ';)', 1: ';)', 2: ';)', 3: ';)', 4: ';)'}
>>> dict.fromkeys(["likes", "retweets"], 0)
{'likes': 0, 'retweets': 0}
The class method .fromkeys
has a gotcha associated with it, though.
Be careful when using mutable values, because the value isn't copied to each key.
It's exactly the same object used over and over:
>>> d = dict.fromkeys(range(3), [])
>>> d
{0: [], 1: [], 2: []}
>>> d[0].append("zero")
>>> d[1].append("one")
>>> d[2] # Shouldn't d[2] be empty?!
['zero', 'one']
>>> d
{0: ['zero', 'one'], 1: ['zero', 'one'], 2: ['zero', 'one']} # π€―
These are just 3 ways of creating a Python dictionary. Soon, I'll send out a Mathspp Insider article talking about all the ways in which you can create dictionaries in Python π Join to keep learning: https://insider.mathspp.com
Here's a quick recap:
dict
accepts an iterable that contains key, value pairs;dict
if you want string keys; and.fromkeys
gives the same value (default is None
) to a bunch of keys.Comment other ways in which you can create a Python π dict!
This article was generated automatically from this thread I published on Twitter @mathsppblog. Then it was edited lightly.
+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!
My book βPydon'tsβ teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here ππ.