Show Menu
Cheatography

Python Dictionairies Cheat Sheet by

Dictionary

A dictionary is changeable and indexed like a list and unordred like a set. A dictio­nairy contains keys and values.

Dictionary example

Car = {
      "­bra­nd": "­For­d",
      "­mod­el": "­Foc­us",
      "­yea­r": 2013
}
print(Car)
>>>­{'b­rand': 'Ford', 'model': 'Focus', 'year': 2013}

The dict() Constr­uctor

thisdict = dict(b­ran­d="F­ord­", model=­"­Foc­us", year=2­013)

Accessing Items

Example 1
x = Car["mo­del­"]
Example 2
x = Car.ge­t("m­ode­l")

Change Values

Car["y­ear­"] = 2019

Check if Key Exists

Check if "­yea­r" is present in the dictio­nary:
if "­yea­r" in Car:
 ­ ­ ­ ­pri­nt(­"Yes, 'year' is one of the keys in the Car dictio­nar­y")

Dictionary Length

print­(le­n(Car))
>>> 3

Adding Items

Car["C­ombined MPG"] = 32
 

Removing Items

Car.p­op(­"­yea­r")
The pop() method removes the item with the specified key name
Car.p­opi­tem()
The popit­em() method removes the last inserted item
del Car["ye­ar"]
The del keyword removes the item with the specified key name

Delete a Dictionary

del Car
print(­Cars) #this will cause an error because "­Car­s" no longer exists.

Return an Empty Dictionary

Car.c­lear()

Copy a Dictionary

Example 1
CarCopy = Car.co­py()
Example 2
CarCopy = dict(Car)
 

Nested Dictio­naries

Cars = {
   ­ ­  "­Car­1":{
 ­ ­ ­ ­  "brand":"Ford",
 ­ ­ ­ ­  "­mod­el":­"­Foc­us"
 ­ ­ ­   },
   ­ ­  "­Car­2":{
 ­ ­ ­ ­  "brand":"Fiat",
 ­ ­ ­ ­  "­mod­el":­"­Pun­to"
 ­ ­ ­   }
 ­ }
Create a nested dictionary from two existing dictio­nai­ries.
Car1 = {
      "­bra­nd": "­For­d",
      "­mod­el": "­Foc­us"
}
Car2 = {
      "­bra­nd": "­Fia­t",
      "­mod­el": "­Pun­to"
}
Cars = {
      "­Car­1": Car1,
      "­Car­2": Car2
}

Help Us Go Positive!

We offset our carbon usage with Ecologi. Click the link below to help us!

We offset our carbon footprint via Ecologi
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter

          More Cheat Sheets by Nouha_Thabet