gpt4 book ai didi

python - dict.fromkeys 是否会一遍又一遍地分配相同的引用?

转载 作者:行者123 更新时间:2023-11-30 23:18:24 24 4
gpt4 key购买 nike

我尝试创建满足我需要的完美字典(包含带有值和列表的字典的字典)。然而,我似乎一遍又一遍地分配相同的引用。

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 引用同一个字典。我不知道我应该如何处理?有什么建议吗?

最佳答案

这种事情通常用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}}

关于python - dict.fromkeys 是否会一遍又一遍地分配相同的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26759062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com