Python. Methods of working with dictionaries




Methods of working with dictionaries


Contents


Search other websites:

1. Built-in iter() function. Get an iterator based on dictionary keys

The iter() method allows you to get an iterator based on dictionary keys. Iterators provide a step-by-step traversal of a list of keys.

According to Python documentation, the general form of using the method is as follows

iterObject = iter(D)

where

  • D – source dictionary;
  • iterObject – iterator.

Example.

# Method iter() - get iterator

# Source dictionary
Colors = { 'Red':1, 'Green':2, 'Blue':3 }

# Get an iterator in iterObj
iterObj = iter(Colors)

# Get the list of keys by iterator
lst = list(iterObj) # lst = ['Red', 'Green', 'Blue']

 

2. The clear() method. Delete all items from the dictionary

The clear() method removes all items from the dictionary.

Example.

# Method clear() - delete all items from the dictionary

# Source dictionary
D = { 'А':1, 'В':2, 'С':3 }

# Clear dictionary D
D.clear() # D = { }

 

3. Method copy(). Return the shallow copy

In case you need to create a copy from the dictionary, the copy() method is used. According to Python documentation, the general form of using the method is as follows

B = A.copy()

where

  • A – source dictionary from which to make a copy;
  • B – The resulting dictionary that is created. This dictionary is a copy of dictionary A.

After the copy() function is executed, changes in one dictionary will not affect changes in another dictionary (dictionaries are located in different memory locations).

Example.

# Method copy() - the copy of dictionary

# Source dictionary
D = { 'А':1, 'В':2, 'С':3 }

# Get a copy of D and write it to D2
D2 = D.copy()

print("D = ", D)
print("D2 = ", D2)

# Change an item in D2 by the key 'B'
D2['В'] = 5 # D2 = {'А': 1, 'В': 5, 'С': 3}

# Add a new pair ('Е':7)
D['E'] = 7 # D = {'A': 1, 'B': 2, 'C': 3, 'E': 7}

print("D = ", D)
print("D2 = ", D2)

Program result is as follows

D = {'A': 1, 'B': 2, 'C': 3}
D2 = {'A': 1, 'B': 2, 'C': 3}
D = {'A': 1, 'B': 2, 'C': 3, 'E': 7}
D2 = {'A': 1, 'B': 5, 'C': 3}

 

4. Method dict.fromkeys(). Create a new dictionary from the given keys and values

The fromkeys() method of the dict class allows you to create a new dictionary from a sequence of specified keys and a certain value. According to Python documentation, the general form of using the method is as follows

D = dict.fromkeys(seq[, value])

where

  • D – newly created dictionary;
  • seq – a sequence of keys, separated by a comma and taken in square brackets;
  • value – the value that is set for all keys in the seq sequence. If value is not set, then None is assigned.

Example.

# Method fromkeys() - create a new dictionary

# 1. values is not set - assigned to None
A = dict.fromkeys([1, 2, 3])
print("A = ", A) # A = {1: None, 2: None, 3: None}

# 2. values is set
B = dict.fromkeys([1, 2], 'Z')
print("B = ", B) # B = {1: 'Z', 2: 'Z', 3: 'Z'}

C = dict.fromkeys(['A', 'B'], [1, 2])
print("C = ", C) # C = {'A': [1, 2], 'B': [1, 2]}

Program result is as follows

A = {1: None, 2: None, 3: None}
B = {1: 'Z', 2: 'Z'}
C = {'A': [1, 2], 'B': [1, 2]}


 

5. The get() method. Get the value of a given key

The get() method is used to get the value for a given key if the key is in the dictionary. If the key is not in the dictionary, then the default value is returned.

According to Python documentation, the general form of using the method is as follows:

D.get(key[, default])

where

  • D – the dictionary from which the value is obtained;
  • key – a key that corresponds to the received value;
  • default – the default value that is set if the key is not in the dictionary.

Example.

# get() method - get the value by key

# Source dictionary
A = { 1:'AA', 2:'BB', 3:'CC' }

# 1. Invoke get() with 1 parameter (without parameter value)
# 1.1. The key is in the dictionary
value = A.get(2) # value = 'BB'

# 1.2. The key is not in the dictionary
value = A.get(5) # value = None

# 2. Invoke get() with 2 parameters
# Set the value by default 'FF'
value = A.get(5, 'FF') # value = FF

 

6. Method items(). Return the view of dictionary items

The items() method returns a new representation of dictionary elements in the form of key:value pairs. The general form of using the method is as follows:

viewObj = D.items()

where

  • viewObj – the resulting view;
  • D – source dictionary.

Example.

# Method items() - return a list of key pairs and values

# Source dictionary
A = { 'First':1, 'Second':2 }

# Create a list of key pairs and values
LA = A.items() # LA = dict_items([('First', 1), ('Second', 2)])

# Another way, using the dict class
LA2 = dict.items(A)

 

7. Method keys(). Get a new view of dictionary keys

The keys() method allows you to get a list of keys. The general form of using the method is as follows:

B = A.keys()

where

  • A – source dictionary;
  • B – view of the keys in the list.

Example.

# Method keys() - get a new view of the keys of the dictionary

# Source dictionary
A = { 1:'One', 2:'Two', 3:'Three' }

# Invoke the keys() method
B = A.keys() # B = dict_keys([1, 2, 3])

 

8. Method pop(). Removing an item from a dictionary with a return value

The pop() method is used to remove an item from the dictionary by the given key. The general form of using the method is as follows:

item = D.pop(key[, default])

where

  • D – source dictionary;
  • item – the value of the element that is pulled from the dictionary;
  • key – a key. If the key key is in the dictionary, then it is deleted from the dictionary and its value is returned in item. If there is no key in the dictionary, then the default value is returned. If the default value is not specified and the key is not in the dictionary, a KeyError exception is thrown;
  • default – the default value that is assigned to the item element if the key key is not found in the dictionary.

Example.

# Method pop() - pull item from dictionary

# Source dictionary
A = { 1:'One', 2:'Two', 3:'Three' }

# 1. Invoke method pop() with 1 parameter
# 1.1. The key is in the dictionary
item = A.pop(2) # A = {1:'One', 3:'Three'}, item = 'Two'

# 1.2. Case when the key is not in the dictionary
# item = A.pop(4) - the exception KeyError: 4 is thrown

# 2. Invoke method pop() with 2 parameters
# Form a new dictionary
A = { 'One':1, 'Two':2, 'Three':3 }

item = A.pop('Two', 5) # A = {'One':1, 'Three':3}, item = 2

# The key is not in the dictionary
item = A.pop('Four', 10) # item = 10

 

9. Method popitem(). Pull an arbitrary pair from the dictionary

The popitem() method removes and returns a random pair (key, value) from the dictionary. The method is used for destructive search of a dictionary, which is often used in set algorithms.

The general form of using the method is as follows:

item = D.popitem()

where

  • D – source dictionary;
  • item – a random pair (key:value) that is pulled from the dictionary.

If the dictionary is empty when calling popitem(), a KeyError error will be generated.

Example.

# Method popitem() - pull random item from dictionary

# Source dictionary
A = { 1:'One', 2:'Two', 3:'Three' }
item = A.popitem() # item = (3, 'Three')

# Dictionary name of the laboratory and offices
B = { 233:'Lecture hall',
      234:'Programming laboratory',
      230:'Network laboratory' }
item = dict.popitem(B) # item = (230, 'Network laboratory')

 

10. Method setdefault(). Set the default item

The setdefault() method allows you to set the default item for a given key. The general form of using the method is as follows

item = D.setdefault(key[, default])

where

  • D – source dictionary;
  • key – the key for which the default value is set.

For this method, various cases of use are possible, which are given in the example.

Example.

# Method setdefault() - set a key by default

# Source dictionary
Colors = { 'Red':1, 'Blue':2, 'Green':3, 'Orange':4 }

# 1. Invoke method with 1 parameter (without argument default)
# 1.1. The key is in the dictionary
item = Colors.setdefault('Green')
# Result:
# item = 3,
# Colors = { 'Red':1, 'Blue':2, 'Green':3, 'Orange':4 }

# 1.2. The key is not in the dictionary
Colors = { 'Red':1, 'Blue':2, 'Green':3, 'Orange':4 }
item = Colors.setdefault('Black')
# Result:
# Colors = {'Red': 1, 'Blue': 2, 'Green': 3, 'Orange': 4, 'Black': None}
# item = None

# 2. Invoke method with 2 parameters
# 2.1. There is no key in the dictionary, then it is added to the dictionary
item = Colors.setdefault('Black', 5)
# Result:
# item = 5,
# Colors = {'Red':1, 'Blue':2, 'Green':3, 'Orange':4, 'Black':5}

# 2.2. No values in the dictionary - no changes
Colors = { 'Red':1, 'Blue':2, 'Green':3, 'Orange':4 }
item = Colors.setdefault('Blue', 8)
# Result:
# item = 2
# Colors = {'Red': 1, 'Blue': 2, 'Green': 3, 'Orange': 4}

 

11. Method update(). Dictionary update

The update() method is used to update the dictionary based on a given list of pairs (key:value). Method returns None.

General form of using the method

D.update([other])

where

  • D – source dictionary;
  • other – the list of pairs (key, value).

Example.

# Method update() - update the dictionary

# Source dictionary
Colors = { 'Red':1, 'Blue':2 }

# 1. The key is not in the dictionary
Colors.update([('Black',7), ('White',9)])
# Colors = {'Red': 1, 'Blue': 2, 'Black': 7, 'White': 9}

# 2. The key is in the dictionary
Colors = { 'Red':1, 'Blue':2 }
Colors.update([('Red', 20),('Blue', 40)])
# Colors = {'Red': 20, 'Blue': 40}

 

12. Method values(). Get a list of values

The values() method allows you to get a list of values from a given dictionary. According to Python documentation, the general form of using the method is as follows:

vals = D.values()

where

  • D – source dictionary;
  • vals – representation of dictionary D values.

When searching for values in a dictionary, a comparison operation occurs. All other types of operations (>,>=, <, <=) will throw a TypeError exception.

Example.

# Method values() - get a list of values

# Source dictionary
Days = { 'Monday':1, 'Tuesday':2, 'Wednesday':3 }

# get the list of values
v = Days.values() # v = dict_values([1, 2, 3])

# convert to list of values
lst = list(v) # lst = [1, 2, 3]

 


Related topics