-8

I have a multivalue dictionary and unique key, I need to have one key for each value

data = {
    "id": [123,456,546,311], 
    "info": ["info1","info2","info3"],       
    .
    .
    .
}

need this answer:

data = {
    "id": [123], 
    "id": [456], 
    "id": [546],
    "id": [311]
    "info":["info1"],
    "info":["info2"],
    "info":["info3"]       

}

thanks, in advance

Ali Nemati
  • 184
  • 5

2 Answers2

1

You cannot have the same key more than once in a dictionary (how would you access it by key?).

You could extract a list of tuples instead, like this:

exploded = [(key, value) for key, values in data.items() for value in values]

Output:

[('id', 123), ('id', 456), ('id', 546), ('id', 311), 
 ('info', 'info1'), ('info', 'info2'), ('info', 'info3')]
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
0

As Olvin Roght already said in the comments, to my knowledge it is not possible to have non-unique keys in a dictionary. In the official Python documentation the following is written:

"It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary)."

(Source: https://docs.python.org/3/tutorial/datastructures.html)

Chris
  • 33
  • 4