Python: Dictionary Methods

By Xah Lee. Date: . Last updated: .

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.
# python 3

# get value of given key

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 dThe opposite of in

Get All Keys, Get All Keys Values

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

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

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

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

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

print(type(kk))
# <class 'dict_keys'>

print(type(vv))
# <class 'dict_values'>

print(type(tt))
# <class 'dict_items'>

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, …
# python 3

# 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, 3: 4, 5: 6, 7: 8, 'aa': 8, 'bb': 9}

Clear, Copy

clear, copy
syntaxmeaning
d.clear()Remove all items. [see Python: dict={} vs dict.clear()]
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 ‹›.
# python 3

# 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, 'b': 2, 'c': 3}

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.

# python 3

# 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'}
# python 3

# example of using zip()

aa = [1, 2, 3, 4]
bb = ["a", "b", "c", "d"]
cc = [10, 20, 30, 40]

print(zip(aa, bb, cc))
# <zip object at 0x106f40b88>

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

Python 2, Loop Thru Key/Value Pairs

These are not in python 3.

syntaxmeaning
d.has_key(k)return true if key k exist in d.
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.

Python List, Tuple, Dictionary

  1. List Basics
  2. Loop Thru List
  3. Map f to List
  4. Copy Nested List
  5. List Comprehension
  6. List Methods
  7. Sort
  8. Dictionary
  9. Loop Thru Dict
  10. Dict Methods
  11. Tuple
  12. Sets, Union, Intersection

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

Python

  1. Python 3 Basics
  2. Python 2 Basics
  3. Python 2 and 3 Difference
  4. Print Version
  5. Builtin Help
  6. Quote String
  7. String Methods
  8. Format String
  9. Operators
  10. Complex Numbers
  11. True, False
  12. if then else
  13. Loop
  14. List Basics
  15. Loop Thru List
  16. Map f to List
  17. Copy Nested List
  18. List Comprehension
  19. List Methods
  20. Sort
  21. Dictionary
  22. Loop Thru Dict
  23. Dict Methods
  24. Tuple
  25. Sets
  26. Function
  27. Closure
  28. 2 Closure
  29. Decorator
  30. Class
  31. Object, ID, Type
  32. List Modules
  33. Write a Module
  34. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. File Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency

Web

  1. Send Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Append String in Loop
  7. Timing f timeit
  8. Keyword Arg Default Value Unstable
  9. Check Page Load Size
  10. Thumbnail Generation