Python Dictionary Cheat Sheet

Posted by

I created a cheat sheet to help when working with common python data types like dictionaries, lists, strings, and tuples.  Knowing how to work with these data types will accelerate your Python development skillset.  I hope you find this useful.

Dictionary Data Type

Some important facts to consider when working with dictionary datatypes:

  • Dictionaries are mutable (they can be changed after creation)
  • Each item in a dictionary is a key:value pair
  • Create Dictionaries using {key:value}
  • A Dictionary can contain different data types
  • A Dictionary cannot have duplicate keys but can have duplicate values

Create Dictionary

#1: Create Empty Dictionary
cars = dict()
	        
#2: Create Dictionary containing same data types#
cars = {'Chevy':'Camaro','Ford':'Mustang','Dodge':'Charger'}
	
#3: Dictionary containing various datatypes#
randominfo = {'cars':['Chevy','Ford','Dodge'], 'owner':'russ', 'age':40}

Access Keys/Values in a Dictionary

cars = {'Chevy':'Camaro','Ford':'Mustang','Dodge':'Charger'}
	
#access dictionary item key to get its value#
print(cars['Ford'])
	
#output: Mustang

Merge a dictionary into another dictionary

cars = {'Chevy':'Camaro','Ford':'Mustang','Dodge':'Charger'}

#new dictionary	
newcars = {'Toyota':'Supra', 'Acura':'NSX'}

#adding newcars dictionary into cars dictionary	
cars.update(newcars)
print(cars)
	
#output: {'Chevy':'Camaro','Ford':'Mustang','Dodge':'Charger','Toyota':'Supra','Acura':'NSX'}

Merge two dictionaries into a new dictionary

#this example uses the unpack operater.
cars = {'Chevy':'Camaro','Ford':'Mustang','Dodge':'Charger'}
newcars = {'Toyota':'Supra', 'Acura':'NSX'}
	
allcars = {**cars, **newcars}

Convert different data types to a dictionary

## Convert list to dictionary ##
      
studentList = ['Student1', 'Russ', 'Student2', 'Jon', 'Student3', 'Mike']
studentDict = { studentList[i]: studentList[i + 1] for i in range(0, len(studentList), 2)}
print(studentDict)
	
#output: {'Student1': 'Russ', 'Student2': 'Jon', 'Student3': 'Mike'}
	
	    
## Convert list of tuples to dictionary ##
        
studentList2 = [('Student1', 'Russ'), ('Student2', 'Jon'), ('Student3', 'Mike')]
studentDict2 = {studentList2[i][0]: studentList2[i][1] for i in range(0, len(studentList2), 1)}
print(studentDict2)
	
#output: {'Student1': 'Russ', 'Student2': 'Jon', 'Student3': 'Mike'}
	
	
## Convert tuple to a dictionary ##
	        
names_and_ages_tup = (('Russ', 45), ('Jon', 46), ('Mike', 49))
names_and_ages_dict = dict(names_and_ages_tup)
print(names_and_ages_dict)
	
#output: {'Russ': 45, 'Jon': 46, 'Mike': 49}

I created a simple python program to provide these details as help content in addition to other data types.

https://github.com/RussMaxwell/PythonHelper

Python Cheat Sheet Series

Thank You!

Russ Maxwell