food = {
'beef': 19,
'chicken_breast': 24.7,
'turkey': 25.9,
'ham': 21,
'salami': 25,
'egg': 13.5,
'duck': 19
}
print(food)
{'beef': 19, 'chicken_breast': 24.7, 'turkey': 25.9, 'ham': 21, 'salami': 25, 'egg': 13.5, 'duck': 19}
print(food['duck'])
19
delicious = 'beef'
print(food[delicious])
19
food = {
'beef': 19,
'chicken_breast': 24.7,
'turkey': 25.9,
'ham': 21,
'salami': 25,
'egg': 13.5,
'duck': 19
}
# Count the number of key:value pairs and put in a variable.
howmany = len(food)
# Show how many.
print(howmany)
7
# Make data dictionary named food
food = {
'beef': 19,
'chicken_breast': 24.7,
'turkey': 25.9,
'ham': 21,
'salami': 25,
'egg': 13.5,
'duck': 19
}
# Is there an egg in food dictionary ?
print('egg' in food)
# Is there an ham in food dictionary ?
print('beans' in food)
True
False
# Look for a person.
delicious = 'turkey'
print(food.get(delicious))
25.9
# Make data dictionary named food
food = {
'beef': 19,
'chicken_breast': 24.7,
'turkey': 25.9,
'ham': 21,
'salami': 25,
'egg': 13.5,
'duck': 19
}
# Look for a food
delicious = 'beans'
print(food.get(delicious))
None
# Print turkey's current value
print(food['turkey'])
# Change the value of turkey key
food['turkey'] = 26.3
#Print turkey key to verify the value has updated
print(food['turkey'])
25.9
26.3
# Make a data dictionary named food.
food = {
'ham': 21,
'turkey': 25.9
}
# Change the value of the turkey key.
food.update({'turkey':26.3})
print(food)
# Update the dictionary with a new property:value pair.
food.update({'salami':25})
print(food)
{'ham': 21, 'turkey': 26.3}
{'ham': 21, 'turkey': 26.3, 'salami': 25}
# Show what's in the data dictionary now.
for value in food.keys():
print(value + " = " + food[value])
Execution error
TypeError: can only concatenate str (not "int") to str
Method | What it Does
----------------------------------------------------------------------------------------+------------------------------------------------------------------------------
Empties the dictionary by remove all keys and values | clear()
copy() | Returns a copy of the dictionary
fromkeys() | Returns a new copy of the dictionary but with only specified keys and values
get() | Returns the value of the specified key, or None if it doesn’t exist
Returns a list of items as a tuple for each key-value pair | items()
keys() | Returns a list of all the keys in a dictionary
Removes the item specified by the key from the dictionary, and stores it in a variable | pop()
Removes the last key-value pair | popitem()
Returns the value of the specified key | setdefault()
update() | Updates the value of an existing key, or adds a new key-value pair
values() | Returns a list of all the values in the dictionary