我试图为我的需要创建一个完美的字典(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。 我不知道该怎么处理? 有什么提示吗?在
这类事情通常用dictionary comprehensions而不是
dict.fromkeys()
来完成:输出:
^{pr2}$下面是使用^{} 获得所需结果的另一种方法:
相关问题 更多 >
编程相关推荐