Beginner Python Cheat Sheet - Dictionaries (Python Crash Course) Flashcards

1
Q
  1. How do you access a dictionary value?

2. What’s another way to access a dictionary value?

A

E.g.
alien_0 = {‘color’: ‘green’, ‘points’: 5}

  1. print(alien_0[‘color’])
    print(alien_0[‘points’])
  2. 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you add a key-value pair in a dictionary?

A

E.g.

alien_0[‘x’] = 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you remove a key value pair?

A

E.g.

del alien_0[‘points’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  1. How do you loop through all of the keys and values?
  2. How do you loop through just the keys?
  3. How do you loop through just the values?
A
  1. for name, language in fav_languages.items():
    print(name + “: “ + language)
  2. for name in fav_languages.keys():
    print(name)
  3. for name in sorted(fav_languages.values()):
    print(name + “: “ + language)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What’s an example of iterating through a nested list of dictionaries?

A
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")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What’s an example of iterating through lists within a dictionary?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you preserve the order in a dictionary?

A

Use the OrderedDict() function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Give an example of using the dict() function

A

> > > # creating empty dictionarydict()
{}

> > > dict(m=8, n=9)
{‘m’: 8, ‘n’: 9}

Through a kwargs type setup (keyword value pairs)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly