1. What is a dictionary data structure?
You may hear about Hash Map in other programming languages. The same concept in python is called the dictionary. Dictionaries are used to store data values in key and value pairs. The advantage of the way key-value storing makes the search very fast especially compared to the way of list iteration. The syntax of a dictionary is like {key: value}, which is unordered, changeable, and has not been allowed duplicated.
2. What you should be aware of?
- Since a key can only correspond to one value, if you put a value into a key multiple times, the later value will replace the previous value.
- The key of dict must be an immutable object, as a result strings or integers are often used as keys. However, variable data structures such as lists cannot be used as keys, because the dictionary structure is based on keys to fetch storage location of the value, this method is called Hashmap.
- A dictionary is not sortable, it may not display items in the defined order
3. The built-in method from a dictionary structure:
Method | Description |
---|---|
clear() | Removes all the elements from the dictionary |
copy() | Returns a copy of the dictionary |
fromkeys() | Returns a dictionary with the specified keys and values |
get() | Returns the value of the specified key |
items() | Returns a list containing the tuple for each key-value pair |
keys() | Returns a list containing the dictionary’s keys |
pop() | Removes the element with the specified key |
popitem() | Removes the last inserted key-value pair |
setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value |
update() | Updates the dictionary with the specified key-value pairs |
values() | Returns a list of all the values in the dictionary |
4. More Examples
# -*- coding: utf-8 -*-
"""
@author:www.jl-blog.com
"""
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
print("\nThis dictionary is :" + str(thisdict))
# get the value by get() method
x = thisdict.get("model")
y = thisdict["model"]
print(x)
print(y)
# To determine how many items (key-value pairs) a dictionary has,
# we can use the len() method.
print(len(thisdict))
# add new key
thisdict["color"] = "green"
print("\nAfter adding new key, now this dictionary is :" + str(thisdict))
# Use copy() to copy the dictionary
# We cannot copy dictionary by typing dict2 = dict1, because dict2 is just a reference to dict1,
# and changes in dict1 will also automatically be made in dict2.
newDict = thisdict.copy()
print("\nThe new dicitonary is:" + str(newDict))