For some reason my small small brain is having problems with this, I have a list of tuples list = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]. Im trying to move these values into a dictionary for parsing later. I have made a few attempts, below the latest of these and im not getting all results into the dict, the dict ends up with the last value iterated (its recreating the dict each time).
people = {}
list = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]
for value in list:
people = {'person': [dict(item.split(":",1) for item in value)]}
You can try this one too:
inlist = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]
d = []
for tup in inlist:
tempDict = {}
for elem in tup:
elem = elem.split(":")
tempDict.update({elem[0]:elem[1]})
d.append({'person':tempDict})
print(d)
Output:
[{'person': {'location': 'brazil', 'name': 'john', 'age': '25'}}, {'person': {'location': 'acme', 'name': 'terry', 'age': '32'}}]
If you want a dictionary with a key person and values the dictionaries with the people's info, then replace d.append({'person':tempDict}) with d.append(tempDict) and add d = {'person':d} right before printing.
Output:
{'person': [{'location': 'brazil', 'name': 'john', 'age': '25'}, {'location': 'acme', 'name': 'terry', 'age': '32'}]}
You can try this:
l = [('name:john','age:25','location:brazil'),('person:terry','age:32','location:acme')]
people = [{c:d for c, d in [i.split(':') for i in a]} for a in l]
Output:
[{'name': 'john', 'age': '25', 'location': 'brazil'}, {'person': 'terry', 'age': '32', 'location': 'acme'}]
First of all try not to call your list list. This name is protected in python and used usually to get a list out of iterators or ranges etc.
I would make a list of people first and then append each person to the people list as separate dictionary as follows:
people = []
my_list = [('name:john','age:25','location:brazil'),('person:terry','age:32','location:acme')]
for tup in my_list:
person = {}
for item in tup:
splitted = item.split(':')
person.update({splitted[0]:splitted[1]})
people.append(person)
The output then would be this:
[{'age': '25', 'location': 'brazil', 'name': 'john'},
{'age': '32', 'location': 'acme', 'person': 'terry'}]
Related
I am iterating through a list of dictionaries. I need to update the values for one specific key in all the dictionaries and I have the new values stored in a list. The list of new values is ordered so that the 1st new value belongs to a key in the 1st dictionary, 2nd new value to a key in the 2nd dictionary, etc.
My data looks something like this:
dict_list = [{'person':'Tom', 'job':'student'},
{'person':'John', 'job':'teacher'},
{'person':'Mary', 'job':'manager'}]
new_jobs = ['lecturer', 'cook', 'driver']
And I want to transform the list of dictionaries using the list of new jobs according to my description into this:
dict_list = [{'person':'Tom', 'job':'lecturer'},
{'person':'John', 'job':'cook'},
{'person':'Mary', 'job':'driver'}]
As I have a very long list of dictionaries I would like to define a function that would do this automatically but I am struggling how to do it with for loops and zip(), any suggestions?
I tried the for loop below. I guess the following code could work if it was possible to index the dictionaries like this dictionary['job'][i] Unfortunately dictionaries don't work like this as far as I know.
def update_dic_list():
for dictionary in dict_list:
for i in range(len(new_jobs)):
dictionary['job'] = new_jobs[i]
print(dict_list)
The output the code above gave me was this:
[{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'teacher'}, {'person': 'Mary', 'job': 'manager'}]
[{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'driver'}, {'person': 'Mary', 'job': 'manager'}]
[{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'driver'}, {'person': 'Mary', 'job': 'driver'}]
If your new_jobs list has the right job for each corresponding entry in the dict list, you could use zip:
dict_list = [{'person':'Tom', 'job':'student'},
{'person':'John', 'job':'teacher'},
{'person':'Mary', 'job':'manager'}]
new_jobs = ['lecturer', 'cook', 'driver']
for d, j in zip(dict_list, new_jobs):
d['job'] = j
print(dict_list)
prints
[{'person': 'Tom', 'job': 'lecturer'}, {'person': 'John', 'job': 'cook'}, {'person': 'Mary', 'job': 'driver'}]
With your loop, for each dictionary, you're going through the new jobs and updating that same dictionary over and over with each of the jobs until the last one. So by the end of it, they'll all be drivers. Because that's the last one.
You can do
dict_list = [{'person':'Tom', 'job':'student'},
{'person':'John', 'job':'teacher'},
{'person':'Mary', 'job':'manager'}]
new_jobs = ['lecturer', 'cook', 'driver']
def update_dic_list():
for job, _dict in zip(new_jobs, dict_list):
_dict['job'] = job
or
def update_dict_list():
for i, job in enumerate(new_jobs):
dict_list[i]['job'] = job
You only need to remove the inner loop because you are changing dictionary key job more than one time for each of item of outer loop:
def update_dic_list():
i = 0
for dictionary in dict_list:
dictionary['job'] = new_jobs[i]
i += 1
print(dict_list)
Or alternatively you could use enumerate:
def update_dic_list():
for i, dictionary in enumerate(dict_list):
dictionary['job'] = new_jobs[i]
print(dict_list)
Output:
[{'person': 'Tom', 'job': 'lecturer'}, {'person': 'John', 'job': 'cook'}, {'person': 'Mary', 'job': 'driver'}]
I need to sort list of dictionaries according to predefined list of values
I am using this part of code, and it will work fine but l_of_dicts has values which are not in a sort_l(predefined list of values)
l_of_dicts = [{'name':'Max','years':18},{'name':'John','years':25},{'name':'Ana','years':19},{'name':'Melis','years':38},{'name':'Ivana','years':38}]
sort_l = ['Ana','Melis','John','Max','Peter']
res = sorted(l_of_dicts , key = lambda ele: sort_l .index(list(ele.values())[0]))
I get an error :
ValueError: 'Ivana' is not in list
Is it posible to ignore that values? or even better extract them to another list?
The script bellow does the job but looks heavier than it should be. Maybe there's easier way to do it.
Script:
def sort_dict_list(dict_list, sorting_list):
result = []
not_used_values = []
temp = {}
for index, dictionary in enumerate(dict_list):
temp[dictionary['name']] = index
for item in sorting_list:
if item in temp.keys():
result.append(dict_list[temp[item]])
else:
not_used_values.append(item)
return result, not_used_values
You could do some preprocessing to store the ordering of only names in l_of_dicts:
l_of_dicts = [{'name': 'Max', 'years': 18}, {'name': 'John', 'years': 25},
{'name': 'Ana', 'years': 19}, {'name': 'Melis', 'years': 38}]
names_in_dicts = {d['name'] for d in l_of_dicts if 'name' in d}
sort_l = ['Ana', 'Melis', 'Ivana', 'John', 'Max', 'Peter']
sort_order = {name: order for order, name in enumerate(sort_l) if name in
names_in_dicts}
print(sort_order) # {'Ana': 0, 'Melis': 1, 'John': 3, 'Max': 4}
sorted_l_of_dicts = sorted(l_of_dicts, key=lambda d: sort_order[d['name']])
print(sorted_l_of_dicts) # [{'name': 'Ana', 'years': 19}, {'name': 'Melis', 'years': 38}, {'name': 'John', 'years': 25}, {'name': 'Max', 'years': 18}]
I am using for loop in python and every loop creates a dictionary. I have the below set of dictionaries created.
{'name': 'xxxx'}
{'name': 'yyyy','age':'28'}
{'name': 'zzzz','age':'27','sex':'F'}
My requirement is to compare all the dictionaries created and find out the missing key values and add the key to missing dictionaries and order every dictionary based on key. Below is the expected output
Expected output:
{'age':'','name': 'xxxx','sex':''}
{'age':'28','name': 'yyyy','sex':''}
{'age':'27','name': 'zzzz','sex':'F'}
How to achieve this in python.
If you want to modify the dicts in-place, dict.setdefault would be easy enough.
my_dicts = [
{'name': 'xxxx'},
{'name': 'yyyy','age':'28'},
{'name': 'zzzz','age':'27','sex':'F'},
]
desired_keys = ['name', 'age', 'sex']
for d in my_dicts:
for key in desired_keys:
d.setdefault(key, "")
print(my_dicts)
prints out
[
{'name': 'xxxx', 'age': '', 'sex': ''},
{'name': 'yyyy', 'age': '28', 'sex': ''},
{'name': 'zzzz', 'age': '27', 'sex': 'F'},
]
If you don't want to hard-code the desired_keys list, you can make it a set and gather it from the dicts before the loop above.
desired_keys = set()
for d in my_dicts:
desired_keys.update(set(d)) # update with keys from `d`
Another option, if you want new dicts instead of modifying them in place, is
desired_keys = ... # whichever method you like
empty_dict = dict.fromkeys(desired_keys, "")
new_dicts = [{**empty_dict, **d} for d in my_dicts]
EDIT based on comments:
This doesn't remove keys that are not there in desired keys.
This will leave only the desired keys:
desired_keys = ... # Must be a set
for d in my_dicts:
for key in desired_keys:
d.setdefault(key, "")
for key in set(d) - desired_keys:
d.pop(key)
However, at that point it might be easier to just create new dicts:
new_dicts = [
{key: d.get(value, "") for key in desired_keys}
for d in my_dicts
]
data = [{'name': 'xxxx'},
{'name': 'yyyy','age':'28'},
{'name': 'zzzz','age':'27','sex':'F'}]
First get the maximum, to get all the keys.
Then use dict.get to get default value as empty string for each of the keys, and sort the dictionary on key, you can combine List-comprehension and dict-comprehension:
allKD = max(data, key=len)
[dict(sorted({k:d.get(k, '') for k in allKD}.items(), key=lambda x:x[0])) for d in data]
OUTPUT:
[{'age': '', 'name': 'xxxx', 'sex': ''},
{'age': '28', 'name': 'yyyy', 'sex': ''},
{'age': '27', 'name': 'zzzz', 'sex': 'F'}]
One approach:
from operator import or_
from functools import reduce
lst = [{'name': 'xxxx'},
{'name': 'yyyy', 'age': '28'},
{'name': 'zzzz', 'age': '27', 'sex': 'F'}]
# find all the keys
keys = reduce(or_, map(dict.keys, lst))
# update each dictionary with the complement of the keys
for d in lst:
d.update(dict.fromkeys(keys - d.keys(), ""))
print(lst)
Output
[{'name': 'xxxx', 'age': '', 'sex': ''}, {'name': 'yyyy', 'age': '28', 'sex': ''}, {'name': 'zzzz', 'age': '27', 'sex': 'F'}]
I'm currently stuck facing some issue with creating a list of dictionaries from a list of lists.
I'm confused with how to append each dictionary to empty list(not in my code). I've known there should be some code after loop processing, but I wasn't able to find out what it is.
l_members = [['Jhon', '19', 'male'],
['Takeru', '20', 'male'],
['Yuri', '22', 'female']
]
d_members = {}
for i in range(len(l_members)):
d_members['name'] = l_members[i][0]
d_members['age'] = l_members[i][1]
d_members['sex'] = l_members[i][2]
l_members.append(d_members)
print(d_members)
Here's a result of print(d_members)
{'name': 'Yuri', 'age': '22', 'sex': 'female'}
my expectation of the result is like below
[{'name': 'Jhon', 'age': '19', 'sex': 'male'},
{'name': 'Takeru', 'age': '20', 'sex': 'male'},
{'name': 'Yuri', 'age': '22', 'sex': 'female'}]
I would appreciate your help, thanks:)
Maybe a list comprehension might work:
d_members = [
{ 'name': name, 'age': age, 'sex': sex }
for name, age, sex in l_members
]
print the list, not the dict you created print(l_members)
create d_members in the loop, to avoid using the same again and again
then reassign to the i box, don't append because it'll only add it
for i in range(len(l_members)):
d_members = {}
d_members['name'] = l_members[i][0]
d_members['age'] = l_members[i][1]
d_members['sex'] = l_members[i][2]
l_members[i] = d_members
print(l_members)
Here are some shorten ways with enumerate, I put some to show you the possiblities
for i in range(len(l_members)):
l_members[i] = {'name': l_members[i][0], 'age': l_members[i][1], 'sex': l_members[i][2]}
for i, member in enumerate(l_members):
l_members[i] = {'name': member[0], 'age': member[1], 'sex': member[2]}
for i, (name, age, sex) in enumerate(l_members):
l_members[i] = {'name': name, 'age': age, 'sex': sex}
You can also use a list-comprehension to avoid using the indices and rebuilt directly the list, along with dict+zip to create the dict :
l_members = [dict(zip(['name', 'age', 'sex'], member)) for member in l_members]
# another one
l_members = [{'name': name, 'age': age, 'sex': sex} for (name, age, sex) in l_members]
As I've mentioned in the comments, this is because your last line of code which prints the value actually prints the d_members variable which will be the last value of the for-loop. You should instead be printing out the l_members variable which you appended the values to in your for-loop.
Additionally, you'll robably find out that the previous records still exist when you print l_members, so you'll have to either:
Remove the initial entries once you're done with the for loop (using list slicing):
l_members = l_members[3:]
Override the value for each iteration of the for loop:
l_members[i] = d_members
Or store the results in a new variable:
ld_members = []
# in your for loop:
ld_members.append(d_members)
Just append the dict to a new list inside the loop as below
list_of_dicts = []
for i in range(len(l_members)):
d_members = {}
d_members['name'] = l_members[i][0]
d_members['age'] = l_members[i][1]
d_members['sex'] = l_members[i][2]
list_of_dicts.append(d_members)
print(list_of_dicts)
litofdict = [{'name': 'Mike', 'surname':'Mikeson', 'age':'15\n'},{'name': 'John', 'surname':'Johnson', 'age':'15\n'},{'name': 'Tomy', 'surname':'Tomson', 'age':'19'}]
How to only remove those '\n' only if they are present (which I am not sure how to check) and return a list consisted only from values that "clear from '\n' of dictionary? Thanks :)
with open("name.txt") as file:
for l in file:
listofdict.append(dict(zip(['name','surname','age']), l.split('|'))))
return listofdict
You could iterate through the dict.items() and strip the values to remove the carriage return, then use a list comprehension to do this for each dict
>>> [{key: val.strip() for key, val in i.items()} for i in listofdict]
[{'surname': 'Mikeson', 'age': '15', 'name': 'Mike'},
{'surname': 'Johnson', 'age': '15', 'name': 'John'},
{'surname': 'Tomson', 'age': '19', 'name': 'Tomy'}]
It's hard to say without seeing your file, but you could do this without any postprocessing by adjusting your file reading
with open("name.txt") as file:
listofdict = [dict(zip(['name','surname','age']), l.strip().split('|')) for l in file]
return listofdict