-1

I have this dictionary in python:

example = {
    "foo": ["1"],
    "bar": ["1","2"]
}

How can i transform efficiently and using Python the variable example to:

example = {
    "foo": "1",
    "bar": ["1","2"]
}

?

Adrian Martinez
  • 479
  • 1
  • 9
  • 17
  • What are you *really* trying to do? You can handle this when reading the dict. – Tatsuyuki Ishi Mar 11 '17 at 05:11
  • I read the data from a url and I get a dictionary with that format. I need to transform such dictionary into JSON and see if other JSON field in postgres have included that data. *I am using django – Adrian Martinez Mar 11 '17 at 05:16

1 Answers1

0

Assuming the dict is not nesting, you can iterate over the dict to modify it: (Python 3, see here for difference)

for key, value in example.items():
  if isinstance(value, list) and len(value) == 1:
    example[key] = value[0]
Tatsuyuki Ishi
  • 3,883
  • 3
  • 29
  • 41