[英]Update a Set inside a nested Dictionary
I'm trying to update a Set in a nested Dictionary, problem is it adds a new Set instead of updating the current Set the 2nd time. 我正在尝试更新嵌套词典中的Set,问题是它添加了一个新Set而不是第二次更新当前Set。
building = {}
building.update({'APT-14D':{}})
building['APT-14D'].setdefault('amenities', set()).add(('hot-water','gas-stove','non-smoke'))
building['APT-14D'].setdefault('amenities', set()).add(('hot-water','non-stove','non-smoke'))
I receive the following: 我收到以下信息:
{'APT-14D': {'amenities': {('hot-water', 'non-stove', 'non-smoke'), ('hot-water', 'gas-stove', 'non-smoke')}}}
instead of: 代替:
{'APT-14D': {'amenities': {('hot-water', 'non-stove', 'non-smoke')}}}
How would I update the current value instead of making a new Set inside the nested dictionary? 我如何更新当前值,而不是在嵌套字典中创建新的Set?
PS The different values are non-stove
and gas-stove
PS:不同的值
non-stove
和gas-stove
You aren't making a new set, you are adding a different tuple to your set . 您不是在创建新集合,而是在集合中添加了另一个元组 。 If you want to add each of the individual elements of your tuple to the set, use
.update
: 如果要将元组的每个单独元素添加到集合中,请使用
.update
:
In [4]: building = {}
...: building.update({'APT-14D':{}})
...: building['APT-14D'].setdefault('amenities', set()).update(('hot-water','gas-stove','non-smoke'))
...: building['APT-14D'].setdefault('amenities', set()).update(('hot-water','non-stove','non-smoke'))
...:
In [5]: building
Out[5]:
{'APT-14D': {'amenities': {'gas-stove',
'hot-water',
'non-smoke',
'non-stove'}}}
Rereading your question, I've notice that isn't even really what you want. 重新阅读您的问题,我注意到这甚至不是您想要的。 It seems now that you don't even want a set, just a tuple, and just replace that tuple with whatever new value comes:
现在看来,您甚至都不想要一个集合,而只想要一个元组,而只需用任何新值替换该元组即可:
In [16]: building = {'APT-14D':{}}
In [17]: building['APT-14D']['amenities'] = ('hot-water','gas-stove','non-smoke')
In [18]: building['APT-14D']['amenities'] = ('hot-water','non-stove','non-smoke')
In [19]: building
Out[19]: {'APT-14D': {'amenities': ('hot-water', 'non-stove', 'non-smoke')}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.