相同的键具有不同的值字典

时间:2017-07-15 05:01:18

标签: python list dictionary

我有一个存储键值对的字典:

s={"one":["two","three","four"],"two":["five","six"],"three":["ten","nine"]}

我希望能够拥有一个带有键的字典"一个"和列表

["test","succesfull"]

所以最终结果将是:

s={"one":["two","three","four"],"two":["five","six"],"three":["ten","nine"],"one":["test","succesfull"]}

我需要能够拥有两个具有不同值的相同键,并且仍然可以独立访问其中任何一个

3 个答案:

答案 0 :(得分:1)

我的方法是再增加一个级别,

s={"one":{"data": ["two","three","four"], "test": "successfull"},"two":["five","six"],"three":["ten","nine"]}

希望满足要求

答案 1 :(得分:1)

我认为最好的方法是将列表列表(列表字典,如果你想要键)作为字典值,在同一个键下存储多个条目,这里是列表列表:

# setup
class dd_list(dict):
    def __missing__(self,k):
        r = self[k] = []
        return r
d = dd_list()

d['one'].append(["two","three","four"])
d['two'].append(["five","six"])
d['three'].append(["ten","nine"])

#adding 'one' key again
d['one'].append(["test","successful"])

print (d)
#{'three': [['ten', 'nine']], 'two': [['five', 'six']], 
#'one': [['two', 'three', 'four'], ['test', 'successful']]}

答案 2 :(得分:0)

python dict键的一个属性是唯一的...

所以在python词典中键应该是唯一的......但是你可以在运行时定义重复...一旦你的dict被存储,副本将被自动删除或者它将被更新。

在运行时,您可以像这样创建

mydict = {"a":1, "b":2, "c":3, "a":3} 

但如果你打印它应该是,

mydict = {"a" :3, "b":2, "c":3}

这里将覆盖最近的值