你必须让你的价值成为一个列表。
例子:
>>> cars = {}
>>> cars['2012'] = ['BMW', ' Fiat']
>>> cars['2013'] = ['Ford', 'Renault']
>>> cars
{'2013': ['Ford', 'Renault'], '2012': ['BMW', ' Fiat']}
>>> cars['2012'].append('Toyota')
>>> cars
{'2013': ['Ford', 'Renault'], '2012': ['BMW', ' Fiat', 'Toyota']}
>>> cars['2012']
['BMW', ' Fiat', 'Toyota']
一个更强大的例子:
from collections import defaultdict
# initiate the dict
cars = defaultdict(list)
# function for adding cars
def add_cars(year, new_cars):
if isinstance(cars, (list, set)):
# if more than 1 new_cars
cars[year].extend(new_cars)
else:
cars[year].append(new_cars)
# add starting cars
add_cars('2012', 'BMW')
add_cars('2013', 'Ford')
# add new cars
add_cars('2012', 'Fiat')
add_cars('2013', 'Renault')
# view
print cars
>>>
defaultdict(<type 'list'>, {'2013': ['Ford', 'Renault'], '2012': ['BMW', 'Fiat']})
还可以选择使用字典执行此操作:
>>> cars = {'2012':['BMW'], '2013':['Ford']}
>>> new_cars = {'2012':['Fiat'], '2013':['Renault']}
>>> for k, v in new_cars.iteritems():
cars[k].extend(v)
>>> cars
{'2013': ['Ford', 'Renault'], '2012': ['BMW', 'Fiat']}