簡體   English   中英

具有不同值字典的相同鍵

[英]same key with different values dictionary

我有一本存儲鍵值對的字典:

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

我希望能夠有一個字典,鍵為“ one”和列表

["test","succesfull"]

因此最終結果將是:

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

我需要能夠擁有兩個具有不同值的相同鍵,並且仍然能夠獨立訪問它們中的任何一個

我的方法是再增加一個級別,

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

希望能滿足要求

我認為最好的方法是將列表列表(如果需要鍵,則為列表字典)作為字典值,將多個條目存儲在同一鍵下,這是列表列表:

# 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']]}

python dict鍵的屬性之一是唯一的...

因此在python字典中,鍵應該是唯一的...但是您可以在運行時定義重復項...一旦存儲了字典,則重復項將自動刪除或更新。

在運行時,您可以這樣創建:

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

但是如果要打印,

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

在這里a將覆蓋最近的值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM