-3

I have dictionary like this:

a = {"RAM": ["25GB", "256GB"], "Storage":  ["25GB"]}

and is there any possible way to make dictionary like this?

wanted_dict = [{"title":"RAM", "items":["25GB", "256GB"]}, {"title":"Storage", "items":["25GB"]}]

i tried to do with for loop but with no result. any advices?

3
  • Your result is actually a list, you can achieve this using the following syntax: wanted_dict = [{"title": key, "items": value} for key, value in a.items()]. Where a is the name of your dictionary. Commented Aug 24, 2021 at 13:06
  • Show your loop and its result. Commented Aug 24, 2021 at 13:07
  • minimal reproducible example for for loop is missing , what does "with no results" mean? Commented Aug 24, 2021 at 13:09

2 Answers 2

3
a = {"RAM": ["25GB", "256GB"], "Storage":  ["25GB"]}
list_a = [{'title': key, 'items': values} for key, values in a.items()]
Sign up to request clarification or add additional context in comments.

3 Comments

can I ask why you like Crabby Fish's answer more?
your answer was good too, but i saw crabbys answer first and thats why i accepted that.
i personally do like using list comprehensions too. so thank you
0

From what I can understand you want to convert the value of a to the value of wanted_dict without hard-coding it. If so, here's the code:

a = {"RAM": ["25GB", "256GB"], "Storage":  ["25GB"]}
b = []

for key in a:
    entry = {"title": key, "items": a[key]}
    b.append(entry)

print(b)

So then you could do:

a = b

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.