2. What’s another way to access a dictionary value?
E.g.
alien_0 = {‘color’: ‘green’, ‘points’: 5}
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’]
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)