Python: Dictionary Methods

By Xah Lee. Date: . Last updated: .

This page is a complete list of Python dictionary methods.

For a basic tutorial, see: Python: Dictionary

Length

length
syntaxmeaning
len(d)return number of items in d. For example, len({"a":8,"b":9})⇒ 2

Get, Set, Delete

get and set and delete
syntaxmeaning
d[k]return the value of key k if exist, else KeyError.
d.get(k)return the value of key k if exist, else return None.
d.get(k,v)return the value of key k if exist, else return v.
d[k] = vSet a value v.
del d[k]Remove the value of key k if exist, else KeyError.
# -*- coding: utf-8 -*-
# python

# example of ‹dictionary›.get(…)

hh = {"a":1, "b":2}

print hh.get("b")   # 2
print hh.get("x")   # None
print hh.get("x", 8)  # 8

Check Existence

test existence
syntaxmeaning
k in dreturn True if d has a key k, else False.
k not in d
d.has_key(k)return true if key k exist in d. This method is deprecated and removed in Python 3.

Get All Keys, Get All Keys Values

Get All Keys, Get All Keys Values
syntaxmeaning
d.keys()return a list that's all key's values. (each element is a new copy)
d.values()return a list that's all key's values. (each element is a new copy)
d.items()return a list of 2-tuples, each is (key, value). (each element is a new copy)
# -*- coding: utf-8 -*-
# python

# example of ‹dictionary›.keys() and ‹dictionary›.keys() and ‹dictionary›.items()

dd = {"a":1, "b":2, "c":3}

kk = dd.keys()
print kk    # ['a', 'c', 'b']

vv = dd.values()
print vv    # [1, 3, 2]

tt = dd.items()
print tt    # [('a', 1), ('c', 3), ('b', 2)]

print type(kk)  # <type 'list'>
print type(vv)  # <type 'list'>
print type(tt)  # <type 'list'>

Loop Thru Key/Value Pairs

Loop Thru Key/Valuese Pairs
syntaxmeaning
d.iterkeys()return a iterator. Each element is a key. A short syntax is iter(d)
d.itervalues()return a iterator. Each element is a key's value.
d.iteritems()return a iterator. Each element is (key, value) pair.
# -*- coding: utf-8 -*-
# python

# example of .iterkeys() and .iterkeys() and .iteritems()

dd = {"a":1, "b":2, "c":3}

ik = dd.iterkeys()
print ik # <dictionary-keyiterator object at 0x7f463d398f70>

iv = dd.itervalues()
print iv   # <dictionary-valueiterator object at 0x7f463d398fc8>

ii = dd.iteritems()
print ii    # <dictionary-itemiterator object at 0x7f463d32f050>

print type(ik)  # <type 'dictionary-keyiterator'>
print type(iv)  # <type 'dictionary-valueiterator'>
print type(ii)  # <type 'dictionary-itemiterator'>

Pop, Update

pop, update
syntaxmeaning
d.pop(k)Remove and return its value if key k exist, else KeyError.
d.pop(k,v)Remove and return its value if key k exist, else v.
d.popitem()Remove and return arbitrary (key, value) pair. If d is empty, KeyError.

Set Value, Update

set value, update
syntaxmeaning
d.setdefault(k)If key k exist, return its value, else, add key with a value of None.
d.setdefault(k, v)If key k exist, return its value, else, insert key with a value of v
d.update(v)Update the dictionary with the key/value pairs from v, overwriting existing keys. Return None. v can be a dictionary or iterable (list, tuple) where each element is iterable of length 2, or can be a key1=val1, key2=val2, …
# -*- coding: utf-8 -*-
# python

# example of ‹dict›.update(…)

aa = {"a":1}

aa.update( [ [3,4], ("a", 2) ] )
print aa    # {'a': 2, 3: 4}

aa.update([(5,6), (7,8)])
print aa    # {'a': 2, 3: 4, 5: 6, 7: 8}

aa.update(aa=8, bb=9)
print aa    # {'a': 2, 'aa': 8, 3: 4, 5: 6, 'bb': 9, 7: 8}

Clear, Copy

clear, copy
syntaxmeaning
d.clear()Remove all items.
d.copy()return a shallow copy of d. [see How to Copy a Nested List in Python?]
d.fromkeys(seq)return a new dictionary with keys from sequence seq (list or tuple). The values are all None.
d.fromkeys(seq, v)return a new dictionary with keys from sequence seq. The values are all ‹›.
# -*- coding: utf-8 -*-
# python

# example of ‹dictionary›.fromkeys(…)

hh = {"a":1, "b":2, "c":3}

h2 = hh.fromkeys([8,9,10])
print h2    # {8: None, 9: None, 10: None}

h3 = hh.fromkeys([8,9,10],"x")
print h3    # {8: 'x', 9: 'x', 10: 'x'}

print hh    # {'a': 1, 'c': 3, 'b': 2}

Dictionary View

view
syntaxmeaning
d.viewitems()a view to a kill 😨
d.viewkeys()a view to a kill 😨
d.viewvalues()a view to a kill 😨

Change Lists into Dictionary

Example of using zip(…). It does transposition.

# -*- coding: utf-8 -*-
# python

# convert 2 lists into a dictionary, use zip()

aa = [1, 2, 3]
bb = ["a", "b", "c"]

print dict(zip(aa, bb))
# ⇒ {1: 'a', 2: 'b', 3: 'c'}
# -*- coding: utf-8 -*-
# python

# example of using zip(). It does transposition.

aa = [1, 2, 3, 4]
bb = ["a", "b", "c", "d"]
cc = [10, 20, 30, 40]
print zip(aa, bb, cc)
# ⇒ [(1, 'a', 10), (2, 'b', 20), (3, 'c', 30), (4, 'd', 40)]

5. Built-in Types — Python v2.7.6 documentation #mapping-types-dict

If you have a question, put $5 at patreon and message me.

Python by Example

  1. Python Basics
  2. Print Version String
  3. Builtin Help

String

  1. Quote String
  2. String Operations
  3. String Methods
  4. Format String

Branching, Loop

  1. True, False
  2. if then else
  3. for, while, Loops

List

  1. List Basics
  2. Loop Thru List
  3. Map Function to List
  4. List Comprehension
  5. List Methods

Dictionary

  1. Dictionary
  2. Loop Thru Dictionary
  3. Dictionary Methods

Function

  1. Function Parameter

Class

  1. Class and Object

Module

  1. List Modules
  2. Write a Module

Unicode

  1. Python + Unicode 🐍
  2. Process Unicode
  3. Convert File Encoding

Common Tasks

  1. Read/Write File
  2. Traverse Directory
  3. Complex Numbers
  4. Get Env Var
  5. JSON

Regex

  1. Regex Basics
  2. Split Line by Regex
  3. Regex Reference

Advanced

  1. Copy Nested List
  2. Tuple vs List
  3. Sets, Union, Intersection
  4. Closure in Python 2
  5. Decorator
  6. Append String in Loop
  7. Timing Functions with timeit
  8. Keyword Argument Default Value Unstable
  1. Find Python Script Path
  2. Manipulate Path
  3. Sort Matrix, Object

Find/Replace

  1. Find/Replace Strings on Multiple Files
  2. Find/Replace Multi-line Strings in a Dir
  3. Find/Replace Mulitple Pairs of Strings
  4. Find/Replace by Regex
  5. Find/Replace Strings in Unicode Files
  6. Python, Perl: Find/Replace Strings in a File

HTML/Web

  1. Sending Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST
  1. A Script to check HTML file size
  2. Thumbnail Generation

Misc

  1. System Call
  2. Decompress Gzip

reference