0

I have difficulties to generate a dictionary that contains identical keys. The actual code:

source = []
key = []
for foto in fotos.split(','):
    source.append(str(foto))
    key.append("source")
dictA = dict(zip(key, source))
pprint(dictA)

The output:

{'source': 'https://www.example.com/fma600/9364f794ed4e5cfc3ba9416ef4ebe065.jpg'}

But I need this dict output:

"pictures":[
  {"source":"http://yourServer/path/to/your/picture.jpg"},
  {"source":"http://yourServer/path/to/your/otherPicture.gif"},
  {"source":"http://yourServer/path/to/your/anotherPicture.png"}
 ]

The problem is: the API needs to duplicate pictures using the same key "source". When I use dict, its not possible to duplicate and create another key with the same name.

martineau
  • 119,623
  • 25
  • 170
  • 301
Loscaos
  • 3
  • 2

2 Answers2

-1

For this specific case, unfortunatly python does not accept duplicate keys for dictionaries.. A possible workaround for the given problem, is to instead using dictionary, try using lists.

For example: listA = list(zip(key, source))

So the output should be something like:

"pictures":[
    ["source", "http://yourServer/path/to/your/picture.jpg"],
    ["source", "http://yourServer/path/to/your/otherPicture.gif"],
    ["source", "http://yourServer/path/to/your/anotherPicture.png"]
]

Those strings could be easily accessed by using the index [0] for the source string, and [1] for the link string.

João Casarin
  • 674
  • 2
  • 9
  • 27
-1

You must use a list containing dict.

Reference URL: In Python, when to use a Dictionary, List or Set?

Please see following code.

dictA = []
for foto in fotos.split(','):
    dictA.append({
        'source':str(foto),
    })
print(dictA)
Canopus
  • 565
  • 3
  • 17
  • Please provide a little explanation; code-only answers, even when correct, don't do much to help the OP figure out what they did wrong. – ShadowRanger Jan 10 '21 at 02:04