値をリストにする必要があります。
例:
>>> 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']}