Python Dictionaries

JK1184 
Created at Jun 15, 2023 09:50:53
Updated at May 09, 2024 16:03:22 
80   0   0   0  

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

Dictionaries are written with curly brackets, and have keys and values:

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

Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

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

Ordered or Unordered?

When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.

Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.


Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.


Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

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

Dictionary Length

To determine how many items a dictionary has, use the len() function:

print(len(thisdict))

Dictionary Items - Data Types

The values in dictionary items can be of any data type:

thisdict = {
  "brand": "Ford",
  "electric": False,
  "year": 1964,
  "colors": ["red", "white", "blue"]
}

type()

From Python's perspective, dictionaries are defined as objects with the data type 'dict':

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

The dict() Constructor

It is also possible to use the dict() constructor to make a dictionary.

thisdict = dict(name = "John", age = 36, country = "Norway")
print(thisdict)

Accessing Items

You can access the items of a dictionary by referring to its key name, inside square brackets:

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

There is also a method called get() that will give you the same result:

x = thisdict.get("model")

Get Keys

The keys() method will return a list of all the keys in the dictionary.

x = thisdict.keys()

The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.

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

x = car.keys()

print(x) #before the change

car["color"] = "white"

print(x) #after the change

Get Values

The values() method will return a list of all the values in the dictionary.

x = thisdict.values()

The list of the values is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the values list.

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

x = car.values()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

Add a new item to the original dictionary, and see that the values list gets updated as well:

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

x = car.values()

print(x) #before the change

car["color"] = "red"

print(x) #after the change

Get Items

The items() method will return each item in a dictionary, as tuples in a list.

x = thisdict.items()

The returned list is a view of the items of the dictionary, meaning that any changes done to the dictionary will be reflected in the items list.

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

x = car.items()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

Add a new item to the original dictionary, and see that the items list gets updated as well:

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

x = car.items()

print(x) #before the change

car["color"] = "red"

print(x) #after the change

Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in thisdict:
  print("Yes, 'model' is one of the keys in the thisdict dictionary")

Change Values

You can change the value of a specific item by referring to its key name:

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

Update Dictionary

The update() method will update the dictionary with the items from the given argument.

The argument must be a dictionary, or an iterable object with key:value pairs.

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

Adding Items

Adding an item to the dictionary is done by using a new index key and assigning a value to it:

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

Update Dictionary

The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.

The argument must be a dictionary, or an iterable object with key:value pairs.

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"color": "red"})

Removing Items

There are several methods to remove items from a dictionary:

The pop() method removes the item with the specified key name:

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

The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):

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

The del keyword removes the item with the specified key name:

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

The clear() method empties the dictionary:

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

Loop Through a Dictionary

You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

for x in thisdict:
  print(x)
for x in thisdict:
  print(thisdict[x])
for x in thisdict.values():
  print(x)
for x in thisdict.keys():
  print(x)
for x, y in thisdict.items():
  print(x, y)

Copy a Dictionary

You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary method copy().

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

Nested Dictionaries

A dictionary can contain dictionaries, this is called nested dictionaries.

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

Or, if you want to add three dictionaries into a new dictionary:

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

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

 

Access Items in Nested Dictionaries

To access items from a nested dictionary, you use the name of the dictionaries, starting with the outer dictionary:

print(myfamily["child2"]["name"])

Dictionary Methods

Python has a set of built-in methods that you can use on dictionaries.

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 value
get()Returns the value of the specified key
items()Returns a list containing a 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

 

Below YouTube content is helpful for better understanding:

 



Tags: Python Python Dictionaries Share on Facebook Share on X

◀ PREVIOUS
Python Sets
▶ NEXT
Python Conditions and If statements
  Comments 0
Login for comment
SIMILAR POSTS

Python Sets (updated at May 09, 2024)

Python Tuples (updated at May 09, 2024)

Python Conditions and If statements (updated at May 09, 2024)

Python Comparison Operators (updated at May 10, 2024)

Python Arithmetic Operators (created at Jun 14, 2023)

Python Lists (updated at May 10, 2024)

Python String Operations (updated at May 10, 2024)

Python While Loops/For Loops (updated at May 09, 2024)

Python Data Types (updated at May 10, 2024)

Python Functions (updated at May 09, 2024)

Python Variables (updated at May 10, 2024)

Python Comments (updated at May 10, 2024)

Python Lambda (updated at May 09, 2024)

Python Arrays (updated at May 09, 2024)

Python Syntax (updated at May 10, 2024)

Python Classes/Objects (updated at May 09, 2024)

Python Getting Started (updated at May 10, 2024)

Python Introduction (created at Jun 12, 2023)

Python Inheritance (updated at May 09, 2024)

What is Python? (updated at Jan 04, 2024)

Python Iterators (updated at May 09, 2024)

Python Polymorphism (updated at May 09, 2024)

Python Scope (updated at May 09, 2024)

Python Modules (updated at May 09, 2024)

Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering (updated at May 12, 2024)

Machine Learning Types and Programming Languages (updated at Nov 29, 2023)

Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship (updated at May 10, 2024)

Mastering Excel Data Manipulation with Python (updated at Apr 26, 2024)

OTHER POSTS IN THE SAME CATEGORY

RegExp example in Python to exclude javascript from HTML code (created at Mar 22, 2024)

Python code to convert from Lunar to Solar (created at Mar 22, 2024)

Python example to download webpage (updated at May 15, 2024)

Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship (updated at May 10, 2024)

Python Modules (updated at May 09, 2024)

Python Scope (updated at May 09, 2024)

Python Polymorphism (updated at May 09, 2024)

Python Iterators (updated at May 09, 2024)

Python Inheritance (updated at May 09, 2024)

Python Classes/Objects (updated at May 09, 2024)

Python Arrays (updated at May 09, 2024)

Python Lambda (updated at May 09, 2024)

Python Functions (updated at May 09, 2024)

Python While Loops/For Loops (updated at May 09, 2024)

Python Conditions and If statements (updated at May 09, 2024)

Python Sets (updated at May 09, 2024)

Python Tuples (updated at May 09, 2024)

Python Comparison Operators (updated at May 10, 2024)

Python Arithmetic Operators (created at Jun 14, 2023)

Python Lists (updated at May 10, 2024)

Python String Operations (updated at May 10, 2024)

Python Data Types (updated at May 10, 2024)

Python Variables (updated at May 10, 2024)

Python Comments (updated at May 10, 2024)

Python Syntax (updated at May 10, 2024)

Python Getting Started (updated at May 10, 2024)

Python Introduction (created at Jun 12, 2023)

What is Python? (updated at Jan 04, 2024)

UPDATES

Aiming for Congressional Award Gold? Your Registration Guide! (created at May 19, 2024)

Digital SAT what you should know (updated at May 17, 2024)

Reflections on a Year of Volunteering at Torrance Wilson Park: Season in 2023-2024 (updated at May 16, 2024)

ChatGPT Reset command and Ignore the Previous Response feature to have a Solid Result (updated at May 16, 2024)

Python example to download webpage (updated at May 15, 2024)

Impact in the theird party cookie on web browser (updated at May 15, 2024)

Why Nike Card Wallets Are a Smart Buy for the Stylishly Practical (updated at May 15, 2024)

How to Rip a Leg that hundreds of people succeeded in (updated at May 15, 2024)

Little Johnny Kang's Taekwondo Journey at the Kukkiwon in 2016 (created at May 15, 2024)

IU's Life Snapshots (updated at May 15, 2024)

Java Tutorials associated with AP Computer Science A (updated at May 15, 2024)

Java Getting Started (updated at May 15, 2024)

Java Syntax (updated at May 15, 2024)

Java Comments (updated at May 15, 2024)

Java Variables (updated at May 15, 2024)

Java Math (updated at May 15, 2024)

Java If ... Else (updated at May 15, 2024)

Java Short Hand If...Else (Ternary Operator) (updated at May 15, 2024)

Java Switch Statements (updated at May 15, 2024)

Loading XML Data with JavaScript (created at May 15, 2024)

Finding Comfort in the Chaos: My LOL Journey on US Servers (updated at May 14, 2024)

Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue (updated at May 13, 2024)

Java Arrays (updated at May 13, 2024)

Meet NewJeans Danielle: The Rising Star with Killer Dance Moves! (updated at May 13, 2024)

IU's 5.16MHz with UAENA (updated at May 12, 2024)

Microsoft Windows commands frquently used (updated at May 12, 2024)

Key Features of the Apache License (updated at May 12, 2024)

Naver Papago - multilingual machine translation service (updated at May 12, 2024)

What is Sitemap? Why do we need it? (updated at May 12, 2024)

What is a smart TV? (updated at May 12, 2024)

Semantic Network - a method of expressing knowledge based on a mesh structure (updated at May 12, 2024)

What is the role of README.md at GitHub/GitLab Repository? (updated at May 12, 2024)

Google Map Link Logic (updated at May 12, 2024)

Flying side kick - Run → Jump → Kick (updated at May 12, 2024)

Las Vegas KÀ by Cirque du Soleil that showed us an exciting fantasy (updated at May 12, 2024)

Physics Areas and Formulas (updated at May 12, 2024)

Statistics Formulas (updated at May 12, 2024)

PreCalculus Formulas for Trigonometry and Math Analysis (updated at May 12, 2024)

Differential/Integral Calculus Formulas (updated at May 12, 2024)

Mean(Averange) and Median based on Global Wealth per Person (updated at May 12, 2024)

Sneaker Style: Perfect Shoes to Wear with Jeans (updated at May 12, 2024)

YouTube Multiview Video Games Dataset from UC Irvine Machine Learning Repository (updated at May 12, 2024)

How to tie your Taekwondo Belt? (updated at May 12, 2024)

Taekwondo Tornado Kick Tutorial - one of my favorite kicks (updated at May 12, 2024)

Exploring the Heartfelt History and Traditions of Valentine's Day (updated at May 12, 2024)

Resell Price $9,400 - Apple Vision Pro Goes Off Right After Launch (updated at May 12, 2024)

Clack Attack - Embracing the Joyful Chaos of Mechanical Keyboards (updated at May 12, 2024)

Indulging in Delight: Waffles and Long Drinks in Seoul, Korea (updated at May 12, 2024)

A House Tour Adventure in the California, US (updated at May 12, 2024)

Base camp for house hunting in Anaheim near Disney Land (updated at May 12, 2024)