Beginner Python Cheat Sheet - Dictionaries (Python Crash Course) Flashcards
- How do you access a dictionary value?
2. What’s another way to access a dictionary value?
E.g.
alien_0 = {‘color’: ‘green’, ‘points’: 5}
- print(alien_0[‘color’])
print(alien_0[‘points’]) - alien_color = alien_0.get(‘color’)
alien_points = alien_0.get(‘points’, 0)
The 0 in this case is what will return if the key does not exist
Get returns none instead of an error if the dictionary doesn’t exist
How do you add a key-value pair in a dictionary?
E.g.
alien_0[‘x’] = 0
How do you remove a key value pair?
E.g.
del alien_0[‘points’]
- How do you loop through all of the keys and values?
- How do you loop through just the keys?
- How do you loop through just the values?
- for name, language in fav_languages.items():
print(name + “: “ + language) - for name in fav_languages.keys():
print(name) - for name in sorted(fav_languages.values()):
print(name + “: “ + language)
What’s an example of iterating through a nested list of dictionaries?
E.g. # Start with an empty list. users = [] # Make a new user, and add them to the list. new_user = { 'last': 'fermi', 'first': 'enrico', 'username': 'efermi', } users.append(new_user) # Make another new user, and add them as well. new_user = { 'last': 'curie', 'first': 'marie', 'username': 'mcurie', } users.append(new_user) # Show all information about each user. for user_dict in users: for k, v in user_dict.items(): print(k + ": " + v) print("\n")
What’s an example of iterating through lists within a dictionary?
E.g.
# Store multiple languages for each person. fav_languages = { 'jen': ['python', 'ruby'], 'sarah': ['c'], 'edward': ['ruby', 'go'], 'phil': ['python', 'haskell'], } # Show all responses for each person. for name, langs in fav_languages.items(): print(name + ": ") for lang in langs: print("- " + lang)
How do you preserve the order in a dictionary?
Use the OrderedDict() function
Give an example of using the dict() function
> > > # creating empty dictionarydict()
{}
> > > dict(m=8, n=9)
{‘m’: 8, ‘n’: 9}
Through a kwargs type setup (keyword value pairs)