0

i have a dictionary that stores key value pairs:

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

i want to be able to to have a dictionary with the key "one" and the list

["test","succesfull"]

so the end result will be:

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

i need to be able to have two of the same keys with different values and still be able to access either of them independently

3 Answers3

2

My approach would be to add one more level,

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

Hope that fulfills the requirments

someone
  • 104
  • 2
  • 10
2

I think the best way to do this is to have lists of lists (dictionaries of lists if you want keys) as the dictionary values, to store multiple entries under the same key, here's the lists of lists:

# 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']]}
ragardner
  • 1,836
  • 5
  • 22
  • 45
0

One of the property of python dict key is unique...

So in python dictionary key should be unique ... but you can able to define duplicate at run time... once your dict is stored the duplicate will automatically removed or it will update .

In run time you can create like this,

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

But if you print it should be,

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

Here a will override with recent value

Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118