-1

I have a dict with n keys. The problem is I don't want a single dictionary, but a list of dictionaries per single key-value pair.

For example:

d = {'a' : -15, 'b' : -71.8333, 'c' : 'a'}

The output I want:

[{'a' : -15},
 {'b' : -71.8333},
 {'c' : 'a'}]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Lareth
  • 41
  • 5

2 Answers2

0

You can iterate over the dict's key-value pairs using dict.items and make a new dict from each one:

d = {'a' : -15, 'b' : -71.8333, 'c' : 'a'}

dicts = []
for key, value in d.items():
    dicts.append({key: value}

Or as a list-comprehension:

dicts = [{key: value} for key, value in d.items()]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
-3

Try this:

d = {'a' : -15, 'b' : -71.8333, 'c' : 'a'}

for i, o in d.items():
    print({i: o})

Will give:

{'a': -15}
{'b': -71.8333}
{'c': 'a'}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
AhOkay
  • 13
  • 3
  • 2
    @MisterMiyagi Not sure if that's rewriting. The question is still the same. The `kwargs` was simply irrelevant (it is just a dict and doesn't add anything to the question). Anyway, at this point this feels like a lost cause. I was just trying to somehow turn this into a canonical as I couldn't find a matching duplicate but maybe it's *too basic* to even be a question... – Tomerikoo Mar 09 '22 at 09:22