I did tried but its saying object is not iterable can anybody fix it?
I actually want to convert list into nested dictionary where year will be my main key
a = ['1980', '1982', '1985', '1986']
b = ['Alex', 'Bob', 'John', 'David']
c = [9.99, 8.55, 7.66, 6.66],[5,7.5,8.5,9,5],[7.5,8.5,9,5],[7.5,8.5,9]
dic = dict(zip(*a,*b,*c))
Output I needed below.
{'1980':{'Alex':9.99,'Bob':8.5,'John':7.6,'David':6.66},'1982':{'Alex':5,'Bob':7.5,'John':8.5,'David':9} …….. So on for every year which is main key.
Thanks for the help
final_dict = {}
year_num = 0
for year in a:
final_dict[year] = {}
person_num = 0
for name in b:
final_dict[year][name]=c[person_num+(4*year_num)]
person_num+=1
year_num+=1
That should work
Related
Given a list of dictionaries like this
a_list = [{'name':'jennifer','roll_no':22}, {'name':'kristina','roll_no':26},
{'name':'jennifer','roll_no':18}, {'name':'kristina','roll_no':33}]
How could this be renamed to
a_list = [{'name':'jennifer','roll_no':22}, {'name':'kristina','roll_no':26},
{'name':'jennifer 1','roll_no':18}, {'name':'kristina 1','roll_no':33}]
You want to construct a new list of dictionaries, but whenever a new dictionary is added that has a 'name' value that was already present, you want to use the next available option.
There's different approaches but one would be:
loop over all the dictionaries in a_list and add them to a new list
before adding them, check some register of used names to see if their name is in there, if not, just add it; if so, get and increase the number associated with it and update the dictionary
So, in code:
a_list = [
{'name':'jennifer','roll_no':22}, {'name':'kristina','roll_no':26},
{'name':'jennifer','roll_no':18}, {'name':'kristina','roll_no':33}
]
names = {}
result = []
for d in a_list:
if (name := d['name']) not in names:
names[name] = 0
else:
names[name] += 1
d['name'] = f'{name} {names[name]}'
result.append(d)
print(result)
Result:
[{'name': 'jennifer', 'roll_no': 22}, {'name': 'kristina', 'roll_no': 26}, {'name': 'jennifer 1', 'roll_no': 18}, {'name': 'kristina 1', 'roll_no': 33}]
I am trying to make a list of dictionaries in python. Why don't these three methods produce the same results?
A = [{}]*2
A[0]['first_name'] = 'Tom'
A[1]['first_name'] = 'Nancy'
print A
B = [{},{}]
B[0]['first_name'] = 'Tom'
B[1]['first_name'] = 'Nancy'
print B
C = [None]*2
C[0] = {}
C[1] = {}
C[0]['first_name'] = 'Tom'
C[1]['first_name'] = 'Nancy'
print C
this is what I get:
[{'first_name': 'Nancy'}, {'first_name': 'Nancy'}]
[{'first_name': 'Tom'}, {'first_name': 'Nancy'}]
[{'first_name': 'Tom'}, {'first_name': 'Nancy'}]
Your first method is only creating one dictionary. It's equivalent to:
templist = [{}]
A = templist + templist
This extends the list, but doesn't make a copy of the dictionary that's in it. It's also equivalent to:
tempdict = {}
A = []
A.append(tempdict)
A.append(tempdict)
All the list elements are references to the same tempdict object.
Barmar has a very good answer why. I say you how to do it well :)
If you want to generate a list of empty dicts use a generator like this:
A = [{}for n in range(2)]
A[0]['first_name'] = 'Tom'
A[1]['first_name'] = 'Nancy'
print (A)
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.
I am having trouble converting a 2d list into a 2d dictionary. I haven't worked much with 2d dictionaries prior to this so please bear with me. I am just wondering why this keeps pulling up a KeyError. In this quick example I would want the dictionary to look like {gender: { name: [food, color, number] }}
2dList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dict = {}
for i in range(len(2dList)):
dict[2dList[i][0]][2dList[i][1]] = [2dList[i][2], 2dList[i][3], 2dList[i][4]]
I keep getting the error message: KeyError: 'male'. I know this is how you add keys for a 1d dictionary, but am unsure regarding 2d dictionaries. I always believed it was:
dictionary_name[key1][key2] = value
You can try this :) It will also work if you have more than one male or female in your List
List = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
d = {}
for l in List:
gender = l[0]
name = l[1]
food = l[2]
color = l[3]
number = l[4]
if gender in d: # if it exists just add new name by creating new key for name
d[gender][name] = [food,color,number]
else: # create new key for gender (male/female)
d[gender] = {name:[food,color,number]}
You are attempting to build a nested dictionary. But are not explicitly initializing the second-layer dictionaries. You need to do this each time, a new key is encountered. Btw, 2dlist is an erroneous way to declare variables in python. This should work for you:
dList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dict = {}
for i in range(len(dList)):
if not dList[i][0] in dict.keys():
dict[dList[i][0]] = {}
dict[dList[i][0]][dList[i][1]] = [dList[i][2], dList[i][3], dList[i][4]]
print(dict)
To get more or less "sane" result use the following (list of dictionaries, each dict is in format {gender: { name: [food, color, number] }}):
l = [['male','josh','chicken','purple','10'], ['female','Jenny','steak','blue','11']]
result = [{i[0]: {i[1]:i[2:]}} for i in l]
print(result)
The output:
[{'male': {'josh': ['chicken', 'purple', '10']}}, {'female': {'Jenny': ['steak', 'blue', '11']}}]
You are getting a KeyError because you are trying to access a non-existing entry on the dictionary with male as the key
You can use defaultdict instead of dict.
from collections import defaultdict
2dList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dict = defaultdict(list)
for i in range(len(2dList)):
dict[2dList[i][0]][2dList[i][1]] = [2dList[i][2], 2dList[i][3], 2dList[i][4]]
Try this
twodList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dic = {twodList[i][0]: {twodList[i][1]: twodList[i][2:]} for i in range(len(twodList))}
As someone mentioned in the comments, you cannot have a variable starting with a number.
list1=[['male','josh','chicken','purple','10'],['female','Jenny','steak','blue','11'],['male','johnson','chicken','purple','10'],['female','jenniffer','steak','blue','11']]
dict = {}
for i in range(len(list1)):
if list1[i][0] in dict:
if list1[i][1] in dict[list1[i][0]]:
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
else:
dict[list1[i][0]][list1[i][1]] = {}
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
else:
dict[list1[i][0]] = {}
if list1[i][1] in dict[list1[i][0]]:
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
else:
dict[list1[i][0]][list1[i][1]] = {}
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
print dict
Above one gives below output:
{"male":{"josh":["chicken","purple","10"],"johnson":["chicken","purple","10"]},"female":{"jenniffer":["steak","blue","11"],"Jenny":["steak","blue","11"]}}
I have a list of names called names. I also have 2 dictionaries that contain a list of nested dictionaries that both have the key names and other data associated with the name. What I want to do is check that the name from the list is in one of the 2 dictionaries, if so, print the data associated only with that name. I can't find any of this stuff in the python docs
names = ['barry','john','george','sarah','lisa','james']
dict1 = {'results':[{'name':'barry','gpa':'2.9','major':'biology'},
{'name':'sarah','gpa':'3.2','major':'economics'},
{'name':'george','gpa':'2.5','major':'english'}]}
dict2 = {'staff':[{'name':'john','position':'Lecturer','department':'economics'},
{'name':'lisa','position':'researcher','department':'physics'},
{'name':'james','position':'tutor','department':'english'}]}
for x in names:
if x in dict1:
print gpa associated with the name
elif x in dict2:
print position associated with the name
The structure you're using for the two dicts isn't very optimal - each contains only a single element, which is a list of the relevant data for each person. If you can restructure those with a separate element per person using the name as a key, this becomes a trivial problem.
dict1 = {'barry': {'gpa':'2.9','major':'biology'},
'sarah': {'gpa':'3.2','major':'economics'},
'george': {'gpa':'2.5','major':'english'}}
dict2 = {'john': {'position':'Lecturer','department':'economics'},
'lisa': {'position':'researcher','department':'physics'},
'james': {'position':'tutor','department':'english'}}
Since it appears you can't get the data in this format, you'll have to convert it:
dict_results = dict((d['name'], d) for d in dict1[results])
if name in dict_results:
print dict_results[name]['gpa']
for _name in names:
if _name in [person['name'] for person in dict1['results']]: pass
elif _name in [person['name'] for person in dict2['staff']]:pass
something like that at least
This should get you an idea:
for name in names:
print name, ":"
print "\t", [x for x in dict2["staff"] if x["name"] == name]
print "\t", [x for x in dict1["results"] if x["name"] == name]
prints
barry :
[]
[{'major': 'biology', 'name': 'barry', 'gpa': '2.9'}]
john :
[{'department': 'economics', 'position': 'Lecturer', 'name': 'john'}]
[]
george :
[]
[{'major': 'english', 'name': 'george', 'gpa': '2.5'}]
sarah :
[]
[{'major': 'economics', 'name': 'sarah', 'gpa': '3.2'}]
lisa :
[{'department': 'physics', 'position': 'researcher', 'name': 'lisa'}]
[]
james :
[{'department': 'english', 'position': 'tutor', 'name': 'james'}]
[]
If you get this data from a database, you should probably rather work on the SQL frontier of the problem. A database is made for operations like that.
names = ['barry','john','george','sarah','lisa','james']
dict1 = {'results':[{'name':'barry','gpa':'2.9','major':'biology'},
{'name':'sarah','gpa':'3.2','major':'economics'},
{'name':'george','gpa':'2.5','major':'english'}]}
dict2 = {'staff':[{'name':'john','position':'Lecturer','department':'economics'},
{'name':'lisa','position':'researcher','department':'physics'},
{'name':'james','position':'tutor','department':'english'}]}
import itertools
for x in itertools.chain(dict1['results'], dict2['staff']):
for n in names:
if n in x.values():
print x
or the 2nd part could be:
ns = set(names)
for x in itertools.chain(dict1['results'], dict2['staff']):
if x['name'] in ns:
print x