cars = {'2012':'BMW', '2013':'Ford'}
new_cars = ['Fiat', 'Renault']
我试图获得:
cars = {'2012':['BMW', 'Fiat'], '2013':['Ford', 'Renault']}
意味着来自0
的位置new_cars
的元素正被添加到位置cars'
的{{1}}项目,依此类推。
我应用了一个我找到的解决方案,但它存在缺陷:
0
任何帮助表示感谢。
答案 0 :(得分:3)
您必须将您的价值列为清单。
示例:
>>> 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']}