-2

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
  • 15,737
  • 15
  • 35
  • 52
Lareth
  • 31
  • 5
  • 2
    Are you looking for ``[{k:v} for k, v in kwargs.items()]``? – MisterMiyagi Mar 08 '22 at 18:49
  • What did you try? Iterating over the key-value pairs in a dictionary is pretty straightforward, as is creating a new dictionary with that key-value pairs. What are you confused about? "Implement this for me" is off topic here because Stack Overflow isn't a free online coding service. Please provide a [mre] and explain your _specific_ issue implementing this yourself – Pranav Hosangadi Mar 09 '22 at 09:18

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
  • 15,737
  • 15
  • 35
  • 52
-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
  • 15,737
  • 15
  • 35
  • 52
AhOkay
  • 1
  • 1
  • 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