dict.fromkeys是否分配相同的引用? [英] Does dict.fromkeys assign the same reference over and over?
本文介绍了dict.fromkeys是否分配相同的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
brands = ['val1','val2','val3 ']
infoBrands = dict.fromkeys(品牌,
dict(dict.fromkeys(['nbOffers','nbBestOffers'],0),
** dict.fromkeys(['higherPrice '],[])))
infoBrands ['val1'] ['nbOffers'] + = 1
打印infoBrands
这里结果:
{'val3':
{'higherPrice':[],
'nbOffers':1,
'nbBestOffers':0},
'val2':
{'higherPrice':[],
'nbOffers':1,
'nbBestOffers':0},
'val1':
{'higherPrice':[],
'nbOffers':1,
'nbBestOffers':0}
}
你可以看到,val1,val2和val3指的是同一个dict。
我不知道该怎么处理它?
任何提示?
解决方案
这种事情通常用 字典理解 ,而不是 dict.fromkeys()
:
brands = ['val1','val2','val3 ']
infoBrands = {brand:{'nbOffers':0,'nbBestOffers':0,'higherPrice':[]}品牌品牌的
}
infoBrands [ 'val1'] ['nbOffers'] + = 1
打印infoBrands
输出: / p>
{'val3':{'higherPrice':[],'nbOffers':0, nbBestOffers':0},
'val2':{'higherPrice':[],'nbOffers':0,'nbBestOffers':0},
'val1':{'higherPrice' ,'nbOffers':1,'nbBestOffers':0}}
I tried to create the perfect dictionary for my needs (dict that's containing a dict with values and a list). However it seems that I assigned the same reference over and over.
brands = ['val1', 'val2', 'val3']
infoBrands = dict.fromkeys(brands,
dict(dict.fromkeys(['nbOffers', 'nbBestOffers'], 0),
**dict.fromkeys(['higherPrice'], [])))
infoBrands['val1']['nbOffers'] += 1
print infoBrands
Here the results:
{'val3':
{'higherPrice': [],
'nbOffers': 1,
'nbBestOffers': 0},
'val2':
{'higherPrice': [],
'nbOffers': 1,
'nbBestOffers': 0},
'val1':
{'higherPrice': [],
'nbOffers': 1,
'nbBestOffers': 0}
}
As you can see, val1, val2 and val3 refer to the same dict. I'm not sure how I should handle it? Any tips?
解决方案
This sort of thing is commonly done with dictionary comprehensions rather thandict.fromkeys()
:
brands = ['val1', 'val2', 'val3']
infoBrands = {brand: {'nbOffers': 0, 'nbBestOffers': 0, 'higherPrice': []}
for brand in brands}
infoBrands['val1']['nbOffers'] += 1
print infoBrands
Output:
{'val3': {'higherPrice': [], 'nbOffers': 0, 'nbBestOffers': 0},
'val2': {'higherPrice': [], 'nbOffers': 0, 'nbBestOffers': 0},
'val1': {'higherPrice': [], 'nbOffers': 1, 'nbBestOffers': 0}}
这篇关于dict.fromkeys是否分配相同的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文