Home > Software design >  put values to dictionary Python
put values to dictionary Python

Time:10-06

I want to put the data extracted from a dictionary into another dictionary. I want tu put what I got from that loop into list_od_id = []

for item in album['tracks']['data']:
    print(item['id'])

list_of_id = []

CodePudding user response:

for item in album['tracks']['data']:
    list_of_id.append(item['id'])

CodePudding user response:

So What I think your trying to say is you want the data of the dictionary to be put in a list.

There are 2 ways of doing this:

1:

dict = {"key1":"value1","key2":"value2","key3":"value3"}
values = []
for i in dict:
    values.append(dict[i])
print("values: "   values)

2:

dict = {"key1":"value1","key2":"value2","key3":"value3"}
values = []
for key, value in dict.items():
    values.append(value)
    print(key   ": "   value)
print(values)

CodePudding user response:

To add a certain value to a list use:

yourList.append(yourValue)

For your Code that would be:

list_of_id =[]
for item in album['tracks']['data']:
    list_of_id.append(item['id'])
print(list_of_id)

EDIT As it seems you confused a list with a dictionary. your list_of_id is has the datatype list. That means it is a Set of values.

A dictionary on the over hand Looks Like this:

myDictionary= {"Key": "value"}

Here you have one value for one Key.

CodePudding user response:

quick solution for create new list of item['id'].

list_of_id = [item['id'] for item in album['tracks']['data']]
  • Related