How to use Python Dictionaries ?

This post explains About Python Dictionary

How to use Python dictionaries?

Dictionary

A dictionary is an unordered, changeable, and indexable array. Dictionaries with curly brackets are written in Python and they have keys and values.

About python dictionary

Using { } curly brackets to create dictionaries, and [ ] square brackets to index them. Separate the key and value between each pair with colons: and with commas. Keys must be quoted As with collections, by reading the relation to the dictionary we will print out. A dictionary maps a collection of items (keys) to another set (values) of objects. A python dictionary is a mapping of unique values keys. Dictionaries are mutable and can be modified. The values pointing to by the keys can be any Python value. Dictionaries are unordered, so the order to include the keys doesn’t necessarily reflect what order they can be reported back to.

Create a new dictionary

Create a dictionary and print it out:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)

Output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Accessing Items

By referring to its key name, inside square brackets, you can access the dictionary items:

Example

To get the value of key “model”, you need to do something like this:

x = thisdict["model"]

Output:

Mustang

There is also a method called get() that will generate the same outcome for you:

x = thisdict.get("model")

Output:

Mustang

Change Values

The value of a particular item can be modified when referring to its key name:

Example

We can change the “year” to 2018 like this:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

thisdict["year"] = 2018

Loop Through a Dictionary

Using a for loop will loop through a dictionary.

If you loop through a dictionary, the return value is the dictionary’s keys, but there are also ways to retrieve the values.

Example

Write the key names, one by one, in the dictionary:

for x in thisdict:
  print(x)

Output:

brand
model
year

Example

To Print all the values in the dictionary, one by one you can do something like this:

for x in thisdict:
  print(thisdict[x])

Output:

Ford
Mustang
1964

Example

If you want to loop through both keys and values, you can use the items() function:

for x, y in thisdict.items():
  print(x, y)

Output:

brand Ford
model Mustang
year 1964

Check if Key Exists

To determine whether a specified key is in a dictionary use the ‘in’ keyword:

Example

You can check if “model” is present in the dictionary, by doing something like this:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in thisdict:
  print("Yes, 'model' is present in thisdict as a key")

Output:

Yes, 'model' is present in thisdict as a key

Dictionary Length

To determine how many properties a dictionary has (key-value pairs), use the len() method.

Example

You can print the number of items in the dictionary, by doing something like this:

print(len(thisdict))

Output:

3

Adding Items

Use a new index key to add an element to the dictionary, and attach a name to it:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

Removing Items

There are several methods of removing elements from a dictionary:

Example

The pop() method removes the element named for the given key:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.pop("model")
print(thisdict)

Output:

{'brand': 'Ford', 'year': 1964}

Example

The pop item approach eliminates the last item added (rather a random element will be extracted in versions before 3.7):

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.popitem()
print(thisdict)

Output:

{'brand': 'Ford', 'model': 'Mustang'}

Example

The del keyword removes the object named after the given key:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict["model"]
print(thisdict)

Output:

{'brand': 'Ford', 'year': 1964}

Example

The del keyword can also absolutely erase the dictionary:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict
print(thisdict) #this will trigger an error, because there is no more "thisdict".

Output:

Traceback (most recent call last):
  File "demo_dictionary_del3.py", line 7, in 
    print(thisdict) #this will trigger an error, because there is no more "thisdict".
NameError: name 'thisdict' is not defined

Example

The keyword clear() empties the dictionary, something like this:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.clear()
print(thisdict)

Output:

{}

Copy a Dictionary

You can’t copy a dictionary just by typing dict2 = dict1, because: dict2 will only be a reference to dict1, so changes made to dict1 will also be made automatically in dict2.

There are ways of making a copy, one approach is to use the built-in Dictionary copy() method.

Example

So you can make a copy of a dictionary with the copy() method if you do something like this:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = thisdict.copy()
print(mydict)

Output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Another way of making a copy is by using the built-in dict() method.

Example

So this time to make a copy of a dictionary with the dict() method, you have to do something like this:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = dict(thisdict)
print(mydict)

Output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Nested Dictionaries

There may also be several dictionaries in a dictionary, this is called nested dictionaries.

Example

To create a dictionary that contains three dictionaries, you have to do something like this:

myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
  }
}

Output:

{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}

And, if you want to nest three already established dictionaries as dictionaries:

Example

In order to create a dictionary from already existing three other dictionaries, you need to do something like this:

child1 = {
  "name" : "Emil",
  "year" : 2004
}
child2 = {
  "name" : "Tobias",
  "year" : 2007
}
child3 = {
  "name" : "Linus",
  "year" : 2011
}

myfamily = {
  "child1" : child1,
  "child2" : child2,
  "child3" : child3
}

Output:

{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}

The dict() Constructor

The dict() constructor may also be used to create a new dictionary:

thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)

Output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Will Post more about Python dictionary Soon. Stay Tuned with Ci3School

Leave a Reply