extract specific value from dictionary of list of dictionary - python

I have dataset like this:
{'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}],
'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]}
what I want to extract is the name of all people:
['john','steve','jack','anna']
How to get these list using python?

my_dict = {
'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}],
'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]
}
You can use a list comprehension it get the name field from each dictionary contained within the sublists (i.e. within the values of the original dictionary).
>>> [d.get('name') for sublists in my_dict.values() for d in sublists]
['john', 'steve', 'jack', 'anna']

Iterate over the dict, then over the values of the current dict:
for d_ in d.values():
for item in d_:
print item['name']
Or in comprehension
names = [item['name'] for d_ in d.values() for item in d_]
print names
['john', 'steve', 'jack', 'anna']

This should do it.
d = {'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}],
'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]}
result = list()
for key in d:
for x in d[key]:
result.append(x['name'])

Many solutions trying same old approach here using two loop:
Here is different approach:
One line solution without any loop:
You can use lambda function with map:
data={'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}],
'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]}
print(list(map(lambda x:list(map(lambda y:y['name'],x)),data.values())))
output:
[['john', 'steve'], ['jack', 'anna']]

name_id = {'project-1': [{'id':'1','name':'john'},{'id':'20','name':'steve'}], 'project-2': [{'id':'6','name':'jack'},{'id':'42','name':'anna'}]}
name_id['project-1'][0]['name'] = 'john'
name_id['project-1'][1]['name'] = 'steve'
name_id['project-2'][0]['name'] = 'jack'
name_id['project-2'][1]['name'] = 'anna'
The ['project-1'] gets the value corresponding to the project-1 key in the dictionary name_id. [0] is the list index for the first element in the dictionary value. ['name'] is also a key, but of the dictionary in the first element of the list. It gives you the final value that you want.

Related

How can I turn a list of values to a list of dictionaries with the same key added to each value?

Let's say I have this list of IDs/values:
Input:
['aaa','bbb','ccc']
I've been stuck on figuring out how I could get the following list of dictionaries. Each dictionary contain the key "id" paired with each of the IDs/values from the list.
Desired Output:
[{'id': 'aaa'}, {'id': 'bbb'}, '{id': 'ccc'}]
You can create a list of dictionaries with a list comprehension:
list_ = ['aaa','bbb','ccc']
output = [{'id': elem} for elem in list_]
You can use list slicing concepts here to get your result.
list1 = ['aaa','bbb','ccc']
finalOutput = [{'id': value} for value in list1]
you can loop and append those dictionaries to list like this:
some_list = ['aaa', 'bbb', 'ccc']
dictionary_list = []
for i in some_list:
dictionary_list.append({'id': i})
You will get a list like you wanted.
['aaa','bbb','ccc']
#place the word 'ID' in front of each element in the list
['ID: '+x for x in ['aaa','bbb','ccc']]

Python3, Tuples in a list, how to get all the values inside them

I have got tuples nested in a list.
Every tuple have 3 objects inside them.
And i have created a dictionary for the first and second object in the list and a dictionary for the first and third object in the list.
My main Problem is that I can not get the values inside the tuples in the list.
I tried a List Comprehension, Which only works for list.
I needed a way to insert the objects to the dictionary.
Variable = [('Bla','Blo','foo'),('Hello','Bye','Seeyou'),('Morning','Afternoon','Evening')]
Dictionary1 = {}
Dictionary2 = {}
for item in Variable:
PreKidsVar[x[len(PreKidsVar)]
This is how I expected it:
Dictionary1 = {'Bla':'Blo','Hello':'Bye','Morning':'Afternoon'}
Dictionary2 = {'Bla':'foo','Hello':'Seeyou','Morning':'Evening'}
You can use dict-comprehension as below:
Dictionary1 = {i[0]:i[1] for i in Variable}
Dictionary2 = {i[0]:i[2] for i in Variable}
Or you can do:
Dictionary1 = {}
Dictionary2 = {}
for i in Variable:
Dictionary1[i[0]] = i[1]
Dictionary2[i[0]] = i[2]
print(Dictionary1)
print(Dictionary2)
You can use below code which uses single for loop:
Variable = [('Bla','Blo','foo'),('Hello','Bye','Seeyou'),('Morning','Afternoon','Evening')]
dict1 ={}
dict2 ={}
for i in Variable:
dict1[i[0]]=i[1]
dict2[i[0]]=i[2]
print(dict1)
print(dict2)
Result:
{'Bla': 'Blo', 'Hello': 'Bye', 'Morning': 'Afternoon'}
{'Bla': 'foo', 'Hello': 'Seeyou', 'Morning': 'Evening'}

Return dictionary keys based on list integer value

I have the following:
my_list = ["7777777", "888888", "99999"]
my_dict = {21058199: '500', 7777777: '500', 21058199: '500'}
I am trying to create a new dictionary which will include the dictionary value (from the original dictionary) that matches the list entry to the dictionary key (in the original dictionary)
for k in my_dict.keys():
if k in my_list:
new_dict.append(k)
print(new_dict)
should return
7777777: '500'
But I'm returning an empty set. I'm not sure what I'm doing wrong here
A dictionary comprehension would provide you what you need.
You need to make sure the types agree (int vs. str)
Unless the list is significantly longer than the dict, it will be much more efficient to iterate over the list and check that key is in the dict than the other way around.
E.g.:
In []:
new_dict = {k: my_dict[k] for k in map(int, my_list) if k in my_dict}
print(new_dict)
Out[]:
{7777777: '500'}
Try like this :
my_list = ["7777777", "888888", "99999"]
my_dict = {21058199: '500', 7777777: '500', 21058199: '500'}
new_dict = {k:my_dict[k] for k in my_dict.keys() if str(k) in my_list}
print(new_dict)
# {7777777: '500'}
Update:
You can also do this with project function from funcy library.
from funcy import project
new_dict = project(my_dict, map(int, my_list))
print(new_dict)
You have to int() the iterator.
my_list = ["7777777", "888888", "99999"]
my_dict = {21058199: '500', 7777777: '500', 21058199: '500'}
for l_i in my_list:
if l_i in my_dict:
print(my_dict[int(l_i)])
Your dictionary keys are of the type 'Int', while your list items are strings. You need to convert one into the other.
for example:
new_dict = {}
for k in my_dict.keys():
if str(k) in my_list:
new_dict[k] = my_dict[k]
Note that you cannot use .append() to add key-value pairs to a dictionary.

Python - Get dictionary element in a list of dictionaries after an if statement

How can I get a dictionary value in a list of dictionaries, based on the dictionary satisfying some condition? For instance, if one of the dictionaries in the list has the id=5, I want to print the value corresponding to the name key of that dictionary:
list = [{'name': 'Mike', 'id': 1}, {'name': 'Ellen', 'id': 5}]
id = 5
if any(m['id'] == id for m in list):
print m['name']
This won't work because m is not defined outside the if statement.
You have a list of dictionaries, so you can use a list comprehension:
[d for d in lst if d['id'] == 5]
# [{'id': 5, 'name': 'Ellen'}]
new_list = [m['name'] for m in list if m['id']==5]
print '\n'.join(new_list)
This will be easy to accomplish with a single for-loop:
for d in list:
if 'id' in d and d['in'] == 5:
print(d['name'])
There are two key concepts to learn here. The first is that we used a for loop to "go through each element of the list". The second, is that we used the in word to check if a dictionary had a certain key.
How about the following?
for entry in list:
if entry['id']==5:
print entry['name']
It doesn't exist in Python2, but a simple solution in Python3 would be to use a ChainMap instead of a list.
import collections
d = collections.ChainMap(*[{'name':'Mike', 'id': 1}, {'name':'Ellen', 'id': 5}])
if 'id' in d:
print(d['id'])
You can do it by using the filter function:
lis = [ {'name': 'Mike', 'id': 1}, {'name':'Ellen', 'id': 5}]
result = filter(lambda dic:dic['id']==5,lis)[0]['name']
print(result)

Loop through list in dictionary with dictionary values

Given a dictionary as such
grouped_data = {"results":[{"id": 101, "name": toto}, {"id": 102, "name": cool}] }
It's a dict that has a list in which it has dictionaries
Hope I'm not confusing you ;), how can I get the results list and loop through each dictionary inside the list to compare the id between them with an if statement.
To get the list:
resultList = grouped_data["results"]
Iterate through the list to get the dictionaries:
for dic in resultList:
# use dic
To get values inside dic:
for dic in resultList:
for key,value in dic.iteritems():
# use key and value
To access the id key, use:
for dic in resultList:
if dic['id'] == somevalue:
# do_something
If you want to "loop through each dictionary inside the list to compare the id between them with an if statement", this is one way to do it.
Example if statement below:
for i in grouped_data["results"]:
if i['id'] > 101:
print (i)
Output:
{'id': 102, 'name': 'cool'}
BTW: You have to convert toto and cool to string unless they are variables which you have declared in your code already.
Not sure what you mean by 'compare the id between them with an if statement'. Many ways to interpret it but here is something that you might use:
print (x for x in grouped_data['results'] if x['id'] > 101).next()
Output:
{'id': 102, 'name': 'cool'}

Categories

Resources