This question already has answers here:
How to get flat list in list comprehension from lists of arbitrary number of elements?
(4 answers)
Closed last year.
How to get the desired result in python?
Base nested dictionary:
dictionary = {"aliceCo": {'name': "Cooper, Alice", 'group': 'finance'},
"bobDe": {'name': "Decker, Bob", 'group': 'hr'},
"caecilEl": {'name': "Elton, Caecil", 'group': 'sales'}
[many similar entrys...]
}
My attempt:
def get_result_list(dictionary, search_string):
return [[key for inner_val in val.values() if search_string in inner_val] for key, val in dictionary.items()]
my_result_list = get_result_list(dictionary, 'sales')
My result:
my_result_list = [[], [], ['caecilEl'], [], [], ...]
Desired result:
my_result_list = ['caecilEl']
I get that I have double lists from the return line, but I found no way to omit them. Also all the empty lists are not wanted. I could go over the result and fix it in another function, but I wish to do it in the inital function.
Thanks for any advice or hints on where to look for a solution!
The empty lists are included because of the nested list.
This function would give the desired result.
def get_result_list(dictionary, search_string):
return [key for key, val in dictionary.items() if search_string in val.values()]
In some cases, it is better to even use a for loop since it is easier to understand and read. I've tried both the solutions:
Using list comprehension:
dnames = {"aliceCo": {'name': "Cooper, Alice", 'group': 'finance'},
"bobDe": {'name': "Decker, Bob", 'group': 'hr'},
"caecilEl": {'name': "Elton, Caecil", 'group': 'sales'}
}
ans = [key for key,value in dnames.items() if value['group'] == 'sales']
ans
Using 2 for loop:
ans = []
for key,value in dnames.items():
for key1,value1 in value.items():
if value1 == 'sales':
ans.append(key)
Using 1 for loop:
ans = []
for key,value in dnames.items():
if value['group] == 'sales':
ans.append(key)
My code is
index = 0
for key in dataList[index]:
print(dataList[index][key])
Seems to work fine for printing the values of dictionary keys for index = 0. However, I can't figure out how to iterate through an unknown number of dictionaries in dataList.
You could just iterate over the indices of the range of the len of your list:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for index in range(len(dataList)):
for key in dataList[index]:
print(dataList[index][key])
or you could use a while loop with an index counter:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
index = 0
while index < len(dataList):
for key in dataList[index]:
print(dataList[index][key])
index += 1
you could even just iterate over the elements in the list directly:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for key in dic:
print(dic[key])
It could be even without any lookups by just iterating over the values of the dictionaries:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
for dic in dataList:
for val in dic.values():
print(val)
Or wrap the iterations inside a list-comprehension or a generator and unpack them later:
dataList = [{'a': 1}, {'b': 3}, {'c': 5}]
print(*[val for dic in dataList for val in dic.values()], sep='\n')
the possibilities are endless. It's a matter of choice what you prefer.
You can easily do this:
for dict_item in dataList:
for key in dict_item:
print(dict_item[key])
It will iterate over the list, and for each dictionary in the list, it will iterate over the keys and print its values.
use=[{'id': 29207858, 'isbn': '1632168146', 'isbn13': '9781632168146', 'ratings_count': 0}]
for dic in use:
for val,cal in dic.items():
print(f'{val} is {cal}')
def extract_fullnames_as_string(list_of_dictionaries):
return list(map(lambda e : "{} {}".format(e['first'],e['last']),list_of_dictionaries))
names = [{'first': 'Zhibekchach', 'last': 'Myrzaeva'}, {'first': 'Gulbara', 'last': 'Zholdoshova'}]
print(extract_fullnames_as_string(names))
#Well...the shortest way (1 line only) in Python to extract data from the list of dictionaries is using lambda form and map together.
"""The approach that offers the most flexibility and just seems more dynamically appropriate to me is as follows:"""
Loop thru list in a Function called.....
def extract_fullnames_as_string(list_of_dictionaries):
result = ([val for dic in list_of_dictionaries for val in
dic.values()])
return ('My Dictionary List is ='result)
dataList = [{'first': 3, 'last': 4}, {'first': 5, 'last': 7},{'first':
15, 'last': 9},{'first': 51, 'last': 71},{'first': 53, 'last': 79}]
print(extract_fullnames_as_string(dataList))
"""This way, the Datalist can be any format of a Dictionary you throw at it, otherwise you can end up dealing with format issues, I found. Try the following and it will still works......."""
dataList1 = [{'a': 1}, {'b': 3}, {'c': 5}]
dataList2 = [{'first': 'Zhibekchach', 'last': 'Myrzaeva'}, {'first':
'Gulbara', 'last': 'Zholdoshova'}]
print(extract_fullnames_as_string(dataList1))
print(extract_fullnames_as_string(dataList2))
Another pythonic solution is using collections module.
Here is an example where I want to generate a dict containing only 'Name' and 'Last Name' values:
from collections import defaultdict
test_dict = [{'Name': 'Maria', 'Last Name': 'Bezerra', 'Age': 31},
{'Name': 'Ana', 'Last Name': 'Mota', 'Age': 31},
{'Name': 'Gabi', 'Last Name': 'Santana', 'Age': 31}]
collect = defaultdict(dict)
# at this moment, 'key' becomes every dict of your list of dict
for key in test_dict:
collect[key['Name']] = key['Last Name']
print(dict(collect))
Output should be:
{'Name': 'Maria', 'Last Name': 'Bezerra'}, {'Name': 'Ana', 'Last Name': 'Mota'}, {'Name': 'Gabi', 'Last Name': 'Santana'}
There are multiple ways to iterate through a list of dictionaries. However, if you are into Pythonic code, consider the following ways, but first, let's use data_list instead of dataList because in Python snake_case is preferred over camelCase.
Way #1: Iterating over a dictionary's keys
# let's assume that data_list is the following dictionary
data_list = [{'Alice': 10}, {'Bob': 7}, {'Charlie': 5}]
for element in data_list:
for key in element:
print(key, element[key])
Output
Alice 10
Bob 7
Charlie 5
Explanation:
for element in data_list: -> element will be a dictionary in data_list at each iteration, i.e., {'Alice': 10} in the first iteration,
{'Bob': 7} in the second iteration, and {'Charlie': 5}, in the third iteration.
for key in element: -> key will be a key of element at each iteration, so when element is {'Alice': 10}, the values for key will be 'Alice'. Keep in mind that element could contain more keys, but in this particular example it has just one.
print(key, element[key]) -> it prints key and the value of element for key key, i.e., it access the value of key in `element.
Way #2: Iterating over a dictionary's keys and values
# let's assume that data_list is the following dictionary
data_list = [{'Alice': 10}, {'Bob': 7}, {'Charlie': 5}]
for element in data_list:
for key, value in element.items():
print(key, value)
The output for this code snippet is the same as the previous one.
Explanation:
for element in data_list: -> it has the same explanation as the one in the code before.
for key, value in element.items(): -> at each iteration, element.items() will return a tuple that contains two elements. The former element is the key, and the latter is the value associated with that key, so when element is {'Alice': 10}, the value for key will be 'Alice', and the value for value will be 10. Keep in mind that this dictionary has only one key-value pair.
print(key, value) -> it prints key and value.
As stated before, there are multiple ways to iterate through a list of dictionaries, but to keep your code more Pythonic, avoid using indices or while loops.
had a similar issue, fixed mine by using a single for loop to iterate over the list, see code snippet
de = {"file_name":"jon","creation_date":"12/05/2022","location":"phc","device":"s3","day":"1","time":"44692.5708703703","year":"1900","amount":"3000","entity":"male"}
se = {"file_name":"bone","creation_date":"13/05/2022","location":"gar","device":"iphone","day":"2","time":"44693.5708703703","year":"2022","amount":"3000","entity":"female"}
re = {"file_name":"cel","creation_date":"12/05/2022","location":"ben car","device":"galaxy","day":"1","time":"44695.5708703703","year":"2022","amount":"3000","entity":"male"}
te = {"file_name":"teiei","creation_date":"13/05/2022","location":"alcon","device":"BB","day":"2","time":"44697.5708703703","year":"2022","amount":"3000","entity":"female"}
ye = {"file_name":"js","creation_date":"12/05/2022","location":"woji","device":"Nokia","day":"1","time":"44699.5708703703","year":"2022","amount":"3000","entity":"male"}
ue = {"file_name":"jsdjd","creation_date":"13/05/2022","location":"town","device":"M4","day":"5","time":"44700.5708703703","year":"2022","amount":"3000","entity":"female"}
d_list = [de,se,re,te,ye,ue]
for dic in d_list:
print (dic['file_name'],dic['creation_date'])
a = []
b = {}
for list1 in tasks:
for dict2 in list1:
b.update(dict2)
a.append(b)
How can I write this code as list comprehension?
I tried this but it didn't work:
a = [ [ b.update(dict2) for dict2 in list1 ] for list1 in tasks ]
my json:
tasks = [[{'tuition_eea_amount': '2083', 'tuition_eea_currency': 'EUR', 'tuition_eea_unit': 'year'},
{'tuition_international_amount': '16200', 'tuition_international_currency': 'EUR', 'tuition_international_unit': 'year'}],
[{'tuition_eea_amount': '2083', 'tuition_eea_currency': 'EUR', 'tuition_eea_unit': 'year'},
{'tuition_international_amount': '16200', 'tuition_international_currency': 'EUR', 'tuition_international_unit': 'year'}]]
I want to convert it into:
a = [[{'tuition_eea_amount': '2083', 'tuition_eea_currency': 'EUR', 'tuition_eea_unit': 'year', 'tuition_international_amount': '16200', 'tuition_international_currency': 'EUR', 'tuition_international_unit': 'year'},
{'tuition_eea_amount': '2083', 'tuition_eea_currency': 'EUR', 'tuition_eea_unit': 'year', 'tuition_international_amount': '16200', 'tuition_international_currency': 'EUR', 'tuition_international_unit': 'year'}]]
There should be one list, with two dictionaries inside. But now it is two lists with two dictionaries inside each of them.
It seems like you want to create a merged dict from all dicts in each list in tasks. For thing you can do:
a = [{k: v for dict2 in list1 for k, v in dict2.items()} for list1 in tasks]
In case of repeating keys between the dicts, this will save the last one encountered.
The dict-comp used here is basically the equivalent of using update in a loop. It iterates over all dicts, and for each updates the new dict with all the key: value pairs. Then te list-comp just does that for all sub-lists in tasks.
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)
I have a list of dictionaries with multiple keys and I would like to get multiple lists each with the indices of the dictionaries, sorted by a particular key.
For example, I have the following list
a = [{"name": "Zoe", "age": 13}, {"name": "Adam", "age": 31}]
I know that I can do the following
from operator import itemgetter
sorted(a, key=itemgetter("name"))
to get the following
[{'name': 'Adam', 'age': 31}, {'name': 'Zoe', 'age': 13}]
but I really want to be able to get two lists with the indices instead:
[1, 0] # order of the elements in `a` as sorted by name
[0, 1] # order of the elements in `a` as sorted by age
My real dictionary has many more key-value pairs and it's more efficient for me to return a and the additional lists with indices as sorted by different keys rather than multiple sorted lists of a.
You can produce a sorted list of indices by producing a range(), and then adjusting the sort key to translate an index to a specific value from a dictionary from the a list:
sorted(range(len(a)), key=lambda i: a[i]['name'])
sorted(range(len(a)), key=lambda i: a[i]['age'])
If you know the keys up front, just loop and produce multiple lists; you could perhaps create a dictionary keyed by each sorting key:
{key: sorted(range(len(a)), key=lambda i: a[i][key]) for key in ('name', 'age')}
The above dictionary comprehension then gives you access to each sorted list based on the sort key alone:
>>> a = [{'name': "Zoe", 'age': 13}, {'name': "Adam", 'age': 31}]
>>> {key: sorted(range(len(a)), key=lambda i: a[i][key]) for key in ('name', 'age')}
{'age': [0, 1], 'name': [1, 0]}
A simple way to do this is to add an index field to the dicts in your list.
from operator import itemgetter
a = [{'name':"Zoe", 'age':13}, {'name':"Adam", 'age':31}]
for i, d in enumerate(a):
d['index'] = i
def get_indices(seq):
return[d['index'] for d in seq]
by_name = sorted(a, key=itemgetter("name"))
print by_name
print get_indices(by_name)
by_age = sorted(a, key=itemgetter("age"))
print by_age
print get_indices(by_age)
output
[{'index': 1, 'age': 31, 'name': 'Adam'}, {'index': 0, 'age': 13, 'name': 'Zoe'}]
[1, 0]
[{'index': 0, 'age': 13, 'name': 'Zoe'}, {'index': 1, 'age': 31, 'name': 'Adam'}]
[0, 1]
Of course, you don't need to keep the sorted lists of dicts, you could just do
by_name = get_indices(sorted(a, key=itemgetter("name")))