-3
cars = {'2012':'BMW', '2013':'Ford'}
new_cars = ['Fiat', 'Renault']

我试图得到:

cars = {'2012':['BMW', 'Fiat'], '2013':['Ford', 'Renault']}

0意味着位置的元素new_cars被添加到cars'位置的项目0等等。

我应用了我在某处找到的解决方案,但它有缺陷:

for car in new_cars:
    for k,v in cars.iteritems():
        cars[k] = [cars[k], car]

任何帮助表示赞赏。

4

1 回答 1

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']}
于 2013-04-28T10:24:19.470 回答