Nesting Lists and Dictionaries

Python bootcamp #100DaysOfCode #myNotes

Dictionaries in Python are used to group together and tag related pieces of information. Stored in {key: value} pairs. They are unordered what means that you can not use an index to retrieve an item. Duplicates (keys) are not allowed. They can contain all the datatypes.

Lists are ordered and the items have a index (position) in the list. This index makes it possible for a List to have duplicates. As the duplicate items will all have a different index.

#example of a list
colors = ['orange', 'black', 'yellow', 'green']

#dictionary example
#the friends name is the key and the drink is the value.
friend_drink = {
  "Petra": "Beer",
  "Eelco": "Wine",
  "Barbara": "Water"
}

#add new items to the dictionary
friend_drink["Pat"] = "Beer"

#edit an item a dictionary 
friend_drink["Frank"]= "Mimosa"

#empty dictionary
friend_drink = {} 

Nesting Lists and Dictionaries:

#Nesting a List in a Dictionary
Wine_log = {
  "Red": ["Merlot", "Pinot Noir", "Cabernet Sauvignon"],
  "White": ["Pinot Grigio", "Moscato", "Chardonnay"],
}

#Nesting Dictionary in a Dictionary

reading_log = {
  "Fantasy": {"books_read": ["Harry Potter", "The Hobbit", "Twilight"], "reviews_done": 1},
  "Biography": {"books_read": ["Becoming", "Steve Jobs", "Dolly parton"], "reviews_done": 2},
}

#Nesting Dictionaries in Lists, reminds me of the movie inception.

reading_log = [
{
  "genre": "Fantasy", 
  "books_read": ["Harry Potter", "The Hobbit", "Twilight"], 
  "reviews_done": 1,
},
{
  "genre": "Biography",
  "books_read": ["Becoming", "Steve Jobs", "Dolly parton"],
  "reviews_done": 2,
},
]

You'll only receive email when LUUS andriessen publishes a new post

More from LUUS andriessen