做dict.fromkeys公司一次又一次地分配同一个参考?

2024-04-25 06:57:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为我的需要创建一个完美的字典(dict包含一个包含值和列表的dict)。不过,我在参考书上似乎是一样的。在

brands = ['val1', 'val2', 'val3']
infoBrands = dict.fromkeys(brands,
                dict(dict.fromkeys(['nbOffers', 'nbBestOffers'], 0),
                     **dict.fromkeys(['higherPrice'], [])))

infoBrands['val1']['nbOffers'] += 1
print infoBrands

结果如下:

^{pr2}$

如您所见,val1、val2和val3指的是同一个dict。 我不知道该怎么处理? 有什么提示吗?在


Tags: 列表字典dictprintval1val2pr2val3
3条回答

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

输出:

^{pr2}$
brands = ['val1', 'val2', 'val3']
init = dict(higher_price=[], nb_offers=0, nb_best_offers=0)
info = {brand: dict(init) for brand in brands}

下面是使用^{}获得所需结果的另一种方法:

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

相关问题 更多 >