I have the following problem:
Given a dictionary in dictionary:
dict1={"user1":{"id":"1", "link":"http://..."}, "user2":{"id":"2", "link":"http://..."}, ... }
I need:
params = {"user_ids":["1","2", ... ]}
I tried:
params ={
"user_ids": dict1.values()["id"]
}
but that's not working. It gives an error: 'dict_values' object is not subscriptable
.
Is there a way to solve this?
CodePudding user response:
You can use loop. Loop using for loop and each one will be inner dict. Now append all the "ids" in a list. After completion of loop, create a dictionary and print it. Your code:
dict1={"user1":{"id":"1", "link":"http://..."}, "user2":{"id":"2", "link":"http://..."} }
f=[]
for i in dict1:
f.append(dict1[i]["id"])
f1={"user_ids":f}
print(f1)
Edit you dict1 accordingly
CodePudding user response:
Using a list comprehension:
user_ids = [d['id'] for d in dict1.values()]
Or using operator.itemgetter
:
from operator import itemgetter
user_ids = list(map(itemgetter('id'), dict1.values()))
CodePudding user response:
If I understand correctly, then the question is that the keys are in the form user digit, then:
dict1 = {"user1":{"id":"1", "link":"http://..."}, "user2":{"id":"2", "link":"http://..."}}
ids = []
for k, v in dict1.items():
if 'user' in k:
for k, v in v.items():
if k == 'id':
ids.append(v)
params = {'users_id': ids}
print(params)
result: {'users_id': ['1', '2']}