我尝试根据自己的需要创建完美的字典(dict包含带有值和列表的字典)。但是,似乎我一遍又一遍地指定相同的参考。
brands = ['val1', 'val2', 'val3']
infoBrands = dict.fromkeys(brands,
dict(dict.fromkeys(['nbOffers', 'nbBestOffers'], 0),
**dict.fromkeys(['higherPrice'], [])))
infoBrands['val1']['nbOffers'] += 1
print infoBrands
结果如下:
{'val3':
{'higherPrice': [],
'nbOffers': 1,
'nbBestOffers': 0},
'val2':
{'higherPrice': [],
'nbOffers': 1,
'nbBestOffers': 0},
'val1':
{'higherPrice': [],
'nbOffers': 1,
'nbBestOffers': 0}
}
如您所见,val1,val2和val3指的是同一个dict。 我不确定我应该怎么处理它? 有什么提示吗?
答案 0 :(得分:2)
此类事情通常使用dictionary comprehensions而不是dict.fromkeys()
:
brands = ['val1', 'val2', 'val3']
infoBrands = {brand: {'nbOffers': 0, 'nbBestOffers': 0, 'higherPrice': []}
for brand in brands}
infoBrands['val1']['nbOffers'] += 1
print infoBrands
输出:
{'val3': {'higherPrice': [], 'nbOffers': 0, 'nbBestOffers': 0},
'val2': {'higherPrice': [], 'nbOffers': 0, 'nbBestOffers': 0},
'val1': {'higherPrice': [], 'nbOffers': 1, 'nbBestOffers': 0}}
答案 1 :(得分:1)
以下是使用dict comprehension
实现所需结果的另一种方法:
brands = ['val1', 'val2', 'val3']
infoBrands = {g: dict({i: 0 for i in ['nbOffers', 'nbBestOffers']},
**{j: [] for j in ['higherPrice']}) for g in brands}
infoBrands['val1']['nbOffers'] += 1
print infoBrands
答案 2 :(得分:0)
brands = ['val1', 'val2', 'val3']
init = dict(higher_price=[], nb_offers=0, nb_best_offers=0)
info = {brand: dict(init) for brand in brands}
答案 3 :(得分:0)
谢谢大家,
编辑:看看@martineau的回答
我做了以下事情:
brands = ['val1', 'val2', 'val3']
infoBrands = dict.fromkeys(brands)
for brand in brands:
infoBrands[brand] = dict([('nbOffers', 0), ('nbBestOffers', 0), ('higherPrice', [])])
infoBrands['val1']['nbOffers'] = 1
print infoBrands
结果:
{'val3':{'higherPrice':[],'nbOffers':0,'nbBestOffers':0}, 'val2':{'higherPrice':[],'nbOffers':0,'nbBestOffers':0},'val1': {'higherPrice':[],'nbOffers':1,'nbBestOffers':0}}