【问题标题】:There is any way to extend a dictionary in python? [duplicate]有什么方法可以在 python 中扩展字典? [复制]
【发布时间】:2020-08-09 00:00:40
【问题描述】:

有没有办法在 python 中扩展字典?
我希望一个键中有多个值。

a = { "abc" : "cbd" , "asd" , "asd"}

【问题讨论】:

  • 字典中的键必须是唯一的。要针对一个键存储多个值,您可以使用列表。像这样a = {"abc": ["abc", "def"]}
  • 使用dict.update(dict)操作
  • 请记住update 将覆盖现有密钥

标签: python dictionary


【解决方案1】:

我希望一个键中包含多个值。

我认为,如果您想在一个键中包含多个值,那么将列表作为值更有意义?

a = { "abc" :["cbd"] , "asd": ["asd"]}
print(a)
#adding new element
if a.get("abc",False): 
   a["abc"].append("new_item")
else:
   a["abc"] = ["new_item"]

print(a)

会返回类似的东西

{'abc': ['cbd'], 'asd': ['asd']}
{'abc': ['cbd', 'new_item'], 'asd': ['asd']}

【讨论】:

    【解决方案2】:

    创建一个list 作为dict 的值并追加:

    a = { "abc" : ['1']
    a["abc"].append('2')
    print(a)  # {'abc': ['1', '2']}
    

    编辑:

    list 中也可以有重复值:

    a = { 'abc' : ['cbd']}
    
    a['abc'].append('asd')
    a['abc'].append('asd')
    
    print(a)
    

    输出:

    {'abc': ['cbd', 'asd', 'asd']} 
    

    【讨论】:

      【解决方案3】:

      你可以用这个:

      a = { "abc" : "cbd"}
      a["abc"] = ["cbd", "asd", "fgh"]  # change the value of "abc" to be a list of your choice of values
      

      在列表中你可以放任何你想要的东西。

      如果您需要键的值,例如“fgh” 你可以这样做:

      a["abc"][2]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-24
        • 1970-01-01
        • 2014-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-12
        • 1970-01-01
        相关资源
        最近更新 更多