PYTHON: A data structure you should know—Dictionary

Spread the love

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?

  1. 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.
  2. 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.
  3. A dictionary is not sortable, it may not display items in the defined order

3. The built-in method from a dictionary structure:

MethodDescription
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))

5. Running Result

Zeren
If you want to know more about me, please get on the about page. :)
Posts created 18

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
error: Content is protected !!