Loop in dict python - python

I have already looked around but have not found any help for this.
This is my dict:
{'id': 1, 'name': 'Studio Pierrot'}
{'id': 29, 'name': 'VAP'}
{'id': 102, 'name': 'FUNimation Entertainment'}
{'id': 148, 'name': 'Hakusensha'}
{'id': 238, 'name': 'AT-X'}
{'id': 751, 'name': 'Marvelous AQL'}
{'id': 1211, 'name': 'Tokyo MX'}
aproducers = an.info['Producers'][0]['name']
for key in aproducers:
print key
The output is like:
S
t
u
d
i
o
...
I want to output just Studio Pierrot,VAP,FUNimation Entertainment...

You’re looping over a string, the single name value of the first producer. You need to loop over the producers instead:
for producer in an.info['Producers']:
print producer['name']

I suggest you to use the methods keys() values() items() and to use nested dicts
for the last question you can just use:
listproducer = []
for producer in an.info['Producers']:
listproducer.append( producer['name'] )

Related

how to insert list of elements into list of dictionaries

I have one list of elements and another list of dictionaries and i want to insert list of elements into each dictionary of list
list_elem = [1,2,3]
dict_ele = [{"Name":"Madhu","Age":25},{"Name":"Raju","Age:24},{""Name":"Mani","Age":12}],
OUTPUT As:
[{"ID":1,"Name":"Madhu","Age":25},{"ID":2,"Name":"Raju","Age:24},{"ID":3,"Name":"Mani","Age":12}]
I have tried this way :
dit = [{"id":item[0]} for item in zip(sam)]
# [{"id":1,"id":2,"id":3}]
dic1 = list(zip(dit,data))
print(dic1)
# [({"id":1},{{"Name":"Madhu","Age":25}},{"id":2},{"Name":"Raju","Age:24},{"id":3},{""Name":"Mani","Age":12})]
What is the most efficient way to do this in Python?
Making an assumption here that the OP's original question has a typo in the definition of dict_ele and also that list_elem isn't really necessary.
dict_ele = [{"Name":"Madhu","Age":25},{"Name":"Raju","Age":24},{"Name":"Mani","Age":12}]
dit = [{'ID': id_, **d} for id_, d in enumerate(dict_ele, 1)]
print(dit)
Output:
[{'ID': 1, 'Name': 'Madhu', 'Age': 25}, {'ID': 2, 'Name': 'Raju', 'Age': 24}, {'ID': 3, 'Name': 'Mani', 'Age': 12}]
dict_ele = [{"Name":"Madhu","Age":25},{"Name":"Raju","Age":24},{"Name":"Mani","Age":12}]
list_elem = [1,2,3]
[{'ID': id, **_dict} for id, _dict in zip(list_elem, dict_ele)]
[{'ID': 1, 'Name': 'Madhu', 'Age': 25}, {'ID': 2, 'Name': 'Raju', 'Age': 24}, {'ID': 3, 'Name': 'Mani', 'Age': 12}]
try this: r = [{'id':e[0], **e[1]} for e in zip(list_elem, dict_ele)]

how do i use more than 1 list index?

how do i use more than 1 list index? like i wanna search through more than just 0 without writing another line that then searches 1, that feels like a workaround
This is my current code, I'm using an API that then I put into a json
>result = response.json()
>{'exercises': [{'tag_id': 317, 'user_input': 'run', 'duration_min': 30, 'met': 9.8, 'nf_calories': 842.8, 'photo': {'highres': 'https://d2xdmhkmkbyw75.cloudfront.net/exercise/317_highres.jpg', 'thumb': 'https://d2xdmhkmkbyw75.cloudfront.net/exercise/317_thumb.jpg', 'is_user_uploaded': False}, 'compendium_code': 12050, 'name': 'running', 'description': None, 'benefits': None}, {'tag_id': 814, 'user_input': 'bike', 'duration_min': 1, 'met': 6.8, 'nf_calories': 19.49, 'photo': {'highres': None, 'thumb': None, 'is_user_uploaded': False}, 'compendium_code': 1020, 'name': 'bicycling', 'description': None, 'benefits': None}]}
then I'm trying to get the 'name', but theres two instances of name and i can only use 0,1,2 etc as the index
>exercises = result['exercises'][0]['name']
>exercisess = result['exercises'][1]['name']
>print(exercises)
>print(exercisess)
>running
>bicycling
is there a way i can search whole thing for keys and get their value without specifically saying 0,1,2 as the index to search
I'm a noob at this sorry if i formatted this question wrong.
You can use list comprehension to add them all to a list then print that.
data = {'exercises': [{'tag_id': 317, 'user_input': 'run', 'duration_min': 30, 'met': 9.8, 'nf_calories': 842.8, 'photo': {'highres': 'https://d2xdmhkmkbyw75.cloudfront.net/exercise/317_highres.jpg', 'thumb': 'https://d2xdmhkmkbyw75.cloudfront.net/exercise/317_thumb.jpg', 'is_user_uploaded': False}, 'compendium_code': 12050, 'name': 'running', 'description': None, 'benefits': None}, {'tag_id': 814, 'user_input': 'bike', 'duration_min': 1, 'met': 6.8, 'nf_calories': 19.49, 'photo': {'highres': None, 'thumb': None, 'is_user_uploaded': False}, 'compendium_code': 1020, 'name': 'bicycling', 'description': None, 'benefits': None}]}
names = [x['name'] for x in data['exercises']]
print(names)
# output: ['running', 'bicycling']
Depends on what you are after.
You use a for loop:
for ex in result['exercises']:
print(ex['name'])
The name ex will refer to each of the elements in turn.

Python list of dict parsing

I have a list of dict which I need to parse into a dict {A:[b,c]}.
iam_profile_association = [{'AssociationId': 'iip-assoc-08c2998aabf8ad37e', 'InstanceId': 'i-078cf2f285a2bb4d3', 'IamInstanceProfile': {'Arn': 'arn:aws:iam:::instance-profile/STANDARD-SSM-INSTANCEPROFILE-us-east-1', 'Id': 'AIPAZTOKUMIFDJ4VGT2FP'}, 'State': 'associated'}, {'AssociationId': 'iip-assoc-0afc8368072fa1d7e', 'InstanceId': 'i-076d4c961d800ba18', 'IamInstanceProfile': {'Arn': 'arn:aws:iam:::instance-profile/STANDARD-SSM-INSTANCEPROFILE-us-east-1', 'Id': 'AIPAZTOKUMIFDJ4VGT2FP'}, 'State': 'associated'}, {'AssociationId': 'iip-assoc-0c46d1f23de061e98', 'InstanceId': 'i-0942731f00ebd33e1', 'IamInstanceProfile': {'Arn': 'arn:aws:iam:::instance-profile/STANDARD-SSM-INSTANCEPROFILE-us-east-1', 'Id': 'AIPAZTOKUMIFDJ4VGT2FP'}, 'State': 'associated'}]
iam_dict = {}
for iam_assoc in iam_profile_association:
iam_dict[iam_assoc['InstanceId']] = [iam_assoc['AssociationId'],iam_assoc['IamInstanceProfile']['Arn']]
print (iam_dict)
iam_dict just prints the first value :
{'i-078cf2f285a2bb4d3': ['iip-assoc-08c2998aabf8ad37e', 'arn:aws:iam::660239311370:instance-profile/STANDARD-SSM-INSTANCEPROFILE-us-east-1']}
Can someone help me in this? I would like to store all the values in this dict format.
Your print is inside the for loop, move it outside (tab it in)
iam_dict = {}
for iam_assoc in iam_profile_association:
iam_dict[iam_assoc['InstanceId']] = ...........
print (iam_dict)
It's tricky to work out more than that from what you are asking. But this would be a good start.

Updating list of dictionaries in python using map

So I have a list that looks like this:
users = [{'id': 11, 'name': 'First'}, {'id': 22, 'name': 'Second'}, {'id':33, 'name': 'Third'}]
What I want to do is to update a users name by passing id, creating new user, and replacing old one with new user.
I want to get list of updated users, like this:
updated_users = list(map(update, users))
If I could send id to update func as argument, what I want to do, would look something like this:
def update(id):
if user['id'] == id:
new_user = some_fun()
user = new_user
return user
How should my update function look like?
I don't know why you want to use map and I think it's a wrong approach because map isn't for this kind of things (you could make it work for sure but it wouldn't be the way to go)
You can do something like that:
users = [{'id': 11, 'name': 'First'}, {'id': 22, 'name': 'Second'}, {'id':33, 'name': 'Third'}]
def update(id, new_name):
for user in users:
if user["id"] == id:
user["name"] = new_name
return
users.append({'id':id,'name':new_name}) # if not exist add user
print(users)
update(11,"Last")
update(1, "New_First")
print(users)
Output:
[{'id': 11, 'name': 'First'}, {'id': 22, 'name': 'Second'}, {'id': 33, 'name': 'Third'}]
[{'id': 11, 'name': 'Last'}, {'id': 22, 'name': 'Second'}, {'id': 33, 'name': 'Third'}, {'id': 1, 'name': 'New_First'}]

faster and more 'pythonic' list of dictionaries

For simplicity, I've provided 2 lists in a list, but I'm actually dealing with a hundred of lists in a list, each containing a sizable amount of dictionaries. I only want to get the value of 'status' key in the 1st dictionary without checking any other dictionaries in that list (since I know they all contain the same value at that key). Then I will perform some sort of clustering within each big dictionary. I need to efficiently concatenate all 'title' values. Is there a way to make my code more elegant and much faster?
I have:
nested = [
[
{'id': 287, 'title': 'hungry badger', 'status': 'High'},
{'id': 437, 'title': 'roadtrip to Kansas','status': 'High'}
],
[
{'id': 456, 'title': 'happy title here','status': 'Medium'},
{'id': 342,'title': 'soft big bear','status': 'Medium'}
]
]
I'd like:
result = [
{
'High': [
{'id': 287, 'title': 'hungry badger'},
{'id': 437, 'title': 'roadtrip to Kansas'}
]
},
{
'Medium': [
{'id': 456, 'title': 'happy title here'},
{'id': 342, 'title': 'soft big bear'}
]
}
]
What I tried:
for oneList in nested:
result= {}
for i in oneList:
a= list(i.keys())
m= [i[key] for key in a if key not in ['id','title']]
result[m[0]]=oneList
for key in a:
if key not in ['id','title']:
del i[key]
from itertools import groupby
result = groupby(sum(nested,[]), lambda x: x['status'])
How it works:
sum(nested,[]) concatenates all your outer lists together into one big list of dictionaries
groupby(, lambda x: x['status']) groups all your objects by their status property
Note itertools.groupby returns a generator (not a list), so if you want to materialize the generator you need to do something like follows.
from itertools import groupby
result = groupby(sum(nested,[]), lambda x: x['status'])
result = {key:list(val) for key,val in result}
You could make a defaultdict for each nested list:
import collections
nested = [
[{'id': 287, 'title': 'hungry badger', 'status': 'High'},
{'id': 437, 'title': 'roadtrip to Kansas','status': 'High'}],
[{'id': 456, 'title': 'happy title here','status': 'Medium'},
{'id': 342,'title': 'soft big bear','status': 'Medium'}] ]
result = []
for l in nested:
r = collections.defaultdict(list)
for d in l:
name = d.pop('status')
r[name].append(d)
result.append(r)
This gives the following result:
>>> import pprint
>>> pprint.pprint(result)
[{'High': [{'id': 287, 'title': 'hungry badger'},
{'id': 437, 'title': 'roadtrip to Kansas'}]},
{'Medium': [{'id': 456, 'title': 'happy title here'},
{'id': 342, 'title': 'soft big bear'}]}]

Categories