java一组字典怎么加入东西,向字典添加新键? - javail的个人空间 - OSCHINA - 中文开源技术交流社区...
创建密钥后,是否可以向Python字典添加密钥? 它似乎没有.add()方法。#1楼dictionary[key] = value#2楼d = {'key':'value'}print(d)# {'key': 'value'}d['mynewkey'] = 'mynewvalue'print(d)# {'mynewkey': 'mynewvalue', 'key': 'value'}#3楼如果要在
创建密钥后,是否可以向Python字典添加密钥? 它似乎没有.add()方法。
#1楼
dictionary[key] = value
#2楼
d = {'key':'value'}
print(d)
# {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d)
# {'mynewkey': 'mynewvalue', 'key': 'value'}
#3楼
如果要在字典中添加字典,可以使用此方法。
示例:将新条目添加到词典和子词典中
dictionary = {}
dictionary["new key"] = "some new entry" # add new dictionary entry
dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
print (dictionary)
输出:
{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}
注意: Python要求您首先添加一个子
dictionary["dictionary_within_a_dictionary"] = {}
在添加条目之前。
#4楼
要同时添加多个键:
>>> x = {1:2}
>>> print x
{1: 2}
>>> d = {3:4, 5:6, 7:8}
>>> x.update(d)
>>> print x
{1: 2, 3: 4, 5: 6, 7: 8}
对于添加单个密钥,可接受的答案具有较少的计算开销。
#5楼
正统语法为d[key] = value ,但是如果键盘缺少方括号键,则可以执行以下操作:
d.__setitem__(key, value)
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)