1

I have a dictionary of the form as follows:

dict={"text":10,"textg":31,"textf":23}

I want this to be converted as follows:

newlist=[{
text:"text",
value:10
},
{
text:"textg",
value:31
},
{
text:"textf",
value:23
}
]

Is there any possible way to do it in python or reactjs?

4 Answers 4

1

You can do like this:

dic={"text":10,"textg":31,"textf":23}
newlist = [{"text": key, "value": val} for key, val in dic.items()]
print(newlist)

Output:

[{'text': 'text', 'value': 10}, {'text': 'textg', 'value': 31}, {'text': 'textf', 'value': 23}]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a for loop to make newList:

dict={"text":10,"textg":31,"textf":23}
newList= []

for item, value in dict.items():
    newList.append({"text": item, "value": value})

Comments

1

In python, you can iterate over a dictionary in many ways, to get its key and value you can use dict.items() Here is a function that would do what you want

def to_list(d):
    l = []
    for k,v in d.items():
        l.append({"text":k, "value":v})
    return l

Or, if you prefer list comprehensions:

def to_list(d):
    return [{"text":k, "value":v} for k,v in d.items()]

Comments

1

The idea behind what you want to do is that you do not realize that a dictionary can be an item in a list. A list can take any data structure as item. Here is a little code that does what you want.

mydict = {'text':10, 'textg': 31, 'textf': 23}
newlist = []
# collect the keys into a list so you can accecss them
dict_keys = [ keys for keys in mydict.keys()]
for keys in dict_keys:
    #create new dictionary instance for each
    new_dict = {}
    new_dict['text'] = keys
    new_dict['value'] = mydict[keys]
    newlist.append(new_dict)

print(newlist) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.