Python Dictionaries

JK JK 2038 
Created at
Updated at  
7,191 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 Facebook X
Comments 0
Similar posts
  1. Python Sets
    7,201
  2. Python Tuples
    7,294
  3. Python Conditions and If statements
    7,215
  4. Python Comparison Operators
    7,380
  5. Python Arithmetic Operators
    7,160
  6. Printing string n times
    7,146
  7. String concatenation by join()
    7,209
  8. Python Lists
    7,496
  9. Python String Operations
    7,577
  10. Python While Loops/For Loops
    7,661
  11. Python Data Types
    7,586
  12. Python Functions
    7,151
  13. Python Variables
    7,556
  14. Python Comments
    7,719
  15. Python Lambda
    7,193
  16. Python Arrays
    7,188
  17. Python Syntax
    7,533
  18. Python Classes/Objects
    7,620
  19. Python Getting Started
    7,598
  20. Python Introduction
    7,182
  21. Python Inheritance
    7,294
  22. What is Python?
    7,844
  23. Python Iterators
    7,197
  24. Python Polymorphism
    7,184
  25. Python Scope
    7,159
  26. Python Modules
    7,205
  27. Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering
    7,489
  28. Machine Learning Types and Programming Languages
    7,357
  29. Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship
    8,108
  30. Mastering Excel Data Manipulation with Python
    7,168
  31. Challenge: One Code Problem Per Day
    1,304
  32. Clean Python Environments: The Power of venv vs. Docker
    1,123
  1. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    1,095
  2. Try...Catch Helps Ignoring Data Type Miss-Match Error in Python
    9,699
  3. RegExp example in Python to exclude javascript from HTML code
    7,141
  4. Python code to convert from Lunar to Solar
    7,951
  5. Python example to download webpage
    8,989
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    1,004
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    885
  3. Michael Jackson's Billie Jean
    419
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    406
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    353
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    386
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    393
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    412
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    1,380
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    567
  11. The Evolution and Production Reality of Agentic AI
    447
  12. How to Activate or Waive Your UIUC Student Health Insurance
    583
  13. Complete Guide to Building a Machine Learning Model
    585
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,636
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    601
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,378
  17. What is Docker? Why is Docker also useful in a development environment?
    832
  18. UIUC 2026-2027 Academic Calendar
    2,076
  19. Open-Source LLMs: The AI Revolution
    1,001
  20. Resume 2.0: Leveling Up for My First Software Gig
    3,055
  21. Not everyone will understand what this man just did
    2,512
  22. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,888
  23. Unpacking IU's Shopper
    995
  24. Jackie Chan's Police Story: The Action Masterpiece
    887
  25. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,236
  26. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,412
  27. Open Databases for Sex Crime Occurrences in the U.S.
    997
  28. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    3,474
  29. My First Day at University of Illinois-Urvana Champaign
    1,395
  30. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,443
  31. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,513
  32. Sipping the Stars: My Starbucks Adventure
    10,210
  33. Exciting explore at Sequoia National Park
    7,881
  34. My Life Shot at Death Valley
    2,089
  35. Ip Man fights with Muay Thai Master
    1,152
  36. Mad Clown - Don't Die
    1,274
  37. How to get Student Enrollment and Degree Verification at UIUC
    5,989
  38. LAX Thanksgiving Rush: A Joyful Reunion
    1,110
  39. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,380
  40. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,167
  41. 10CM - To Reach You (너에게 닿기를)
    1,344
  42. Feeling weak? Transform yourself at the UIUC ARC!
    1,765
  43. BOYNEXTDOOR - If I Say I Love You
    1,402
  44. The Future of Software Engineer - AI Engineering
    1,125
  45. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,133
  46. Lie - Legend song by BIGBANG
    8,025
  47. Why ROLLBACK is useful when you work with Google Gemini CLI?
    1,120
  48. Reimbursement after Vaccination at McKinley Health Center
    1,245
  49. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    1,172
  50. Common Questions from UIUC school life in terms of CS Program
    1,356