You are on page 1of 4

2021/5/13 4.3. Dicts — Python Notes (0.14.

0)

Python Notes (0.14.0)


P R E VIOUS | N E X T | M O D ULES | I N D EX

4.3. Dicts
SEARCH
Contents
Dicts Go
Quick example Enter search terms
Methods to query information or a module, class or
Methods to create new dictionary function name.
iterators This page: Show
Views source.
comparison TABLE OF
CONTENTS
1. Quick Start /
4.3.1. Quick example Tutorial
A dictionary is a sequence of items. Each item is a pair
2. Variables,
made of a key and a value. Dictionaries are not sorted.
expressions,
You can access to the list of keys or values
statements,
independently.
types
>>> d = {'first':'string value', 'second':[1,2]} 1. Iterators
>>> d.keys()
['first', 'second'] 2. Generators
>>> d.values()
['string value', [1, 2]] 3. Exceptions
You can access to the value of a given key as follows: 4. Decorators
>>> d['first'] 5. Classes
'string value'
6. Namespace and
Warning
scoping rules
You can not have duplicate keys in a dictionary
7. Packaging
Warning
8. Notes about
dictionary have no concept of order among elements sorting lists and
dictionaries

4.3.2. Methods to query information 9. Notes about


booleans and
In addition to keys and values methods, there is also logical operators
the items method that returns a list of items of the
form (key, value). The items are not returned in any 10. Notes on

particular order:

>>> d = {'first':'string value', 'second':[1,2]}


>>> d.items()
[('a', 'string value'), ('b', [1, 2])]

https://thomas-cokelaer.info/tutorials/python/dicts.html 1/4
2021/5/13 4.3. Dicts — Python Notes (0.14.0)

The iteritems method works in much the same way,


but returns an iterator instead of a list. See iterators
section for an example.
You can check for the existence of a specific key with
has_key:

>>> d.has_key('first')
True
SEARCH

The expression d.has_key(k) is equivalent to k in d. Go


The choice of which to use is largely a matter of taste. Enter search terms

In order to get the value corresponding to a specific or a module, class or

key, use get or pop: function name.

This page: Show


>>> d.get('first') # this method can set an optio
'string value'
source.
TABLE OF
It is useful for things like adding up numbers:
CONTENTS
1. Quick Start /
sum[value] = sum.get(value, 0) + 1 Tutorial

See also 2. Variables,


setdefault, collections expressions,
statements,
The difference between get and pop is that pop also types
removes the corresponding item from the dictionary: 1. Iterators
>>> d.pop('first') 2. Generators
'string value'
>>> d 3. Exceptions
{'second': [1, 2]}

Finally, popitem removes and returns a pair (key, 4. Decorators

value); you do not choose which one because a 5. Classes


dictionary is not sorted
6. Namespace and
>>> d.popitem() scoping rules
('a', 'string value')
>>> d 7. Packaging
{'second': [1, 2]}
8. Notes about
sorting lists and
4.3.3. Methods to create new dictionaries
dictionary 9. Notes about

Since dictionaries (like other sequences) are objects, booleans and

you should be careful when using the affectation sign: logical operators

10. Notes on
>>> d1 = {'a': [1,2]}
>>> d2 = d1
>>> d2['a'] = [1,2,3,4]
>>> d1['a]
[1,2,3,4]

https://thomas-cokelaer.info/tutorials/python/dicts.html 2/4
2021/5/13 4.3. Dicts — Python Notes (0.14.0)

To create a new object, use the copy method (shallow


copy):

>>> d2 = d1.copy()

See also
copy.deepcopy()
SEARCH
You can clear a dictionary (i.e., remove all its items)
using the clear() method: Go
Enter search terms
>>> d2.clear() or a module, class or
{}
function name.
The clear() method deletes all items whereas del() This page: Show
deletes just one: source.
>>> d = {'a':1, 'b':2, 'c':3} TABLE OF
>>> del d['a'] CONTENTS
>>> d.clear()
1. Quick Start /
Create a new item with default value (if not provided, Tutorial
None is the default):
2. Variables,
>>> d2.setdefault('third', '') expressions,
>>> d2['third']
statements,
''
types
Create a dictionary given a set of keys:
1. Iterators
>>> d2.fromkeys(['first', 'second'])
2. Generators
another syntax is to start from an empty dictionary:
3. Exceptions
>>> {}.fromkeys(['first', 'second'])
{'first': None, 'second': None} 4. Decorators

Just keep in ,ind thqt the fromkeys() method creates a 5. Classes


new dictionary with the given keys, each with a default
6. Namespace and
corresponding value of None.
scoping rules

4.3.3.1. Combining dictionaries 7. Packaging

Given 2 dictionaries d1 and d2, you can add all pairs of 8. Notes about
key/value from d2 into d1 by using the update method sorting lists and
(instead of looping and assigning each pair yourself: dictionaries

>>> d1 = {'a':1} 9. Notes about


>>> d2 = {'a':2; 'b':2} booleans and
>>> d1.update(d2)
>>> d1['a'] logical operators
2
>>> d2['b'] 10. Notes on
2

The items in the supplied dictionary are added to the


old one, overwriting any items there with the same
keys.

https://thomas-cokelaer.info/tutorials/python/dicts.html 3/4
2021/5/13 4.3. Dicts — Python Notes (0.14.0)

4.3.4. iterators
Dictionary provides iterators over values, keys or
items:

>>> [x for x in t.itervalues()]


['string value', [1, 2]]
>>>
>>> [x for x in t.iterkeys()] SEARCH
['first', 'csecond']
>>> [x for x in t.iteritems()] Go
[('a', 'string value'), ('b', [1, 2])]
Enter search terms
or a module, class or
See also
function name.
Iterators
This page: Show
source.
4.3.5. Views TABLE OF
CONTENTS
viewkeys, viewvalues, viewitems are set-like
1. Quick Start /
objects providing a view on D’s keys, values or items.
Tutorial

2. Variables,
4.3.6. comparison expressions,
you can compare dictionaries! Python first compares statements,
the sorted key-value pairs. It first sorts dictionaries by types
key and comapre their initial items. If the items hae 1. Iterators
different values, Python figures out the comparison
between them. Otherwise, the second items are 2. Generators
compared and so on. 3. Exceptions

4. Decorators

5. Classes

6. Namespace and
scoping rules

7. Packaging

8. Notes about
sorting lists and
dictionaries

9. Notes about
booleans and
logical operators

10. Notes on

https://thomas-cokelaer.info/tutorials/python/dicts.html 4/4

You might also like