I have a list and i would like to convert it into a dictionary such that key:value pairs should be like
{'apple':87, 'fan':88 ,'jackal':89,...}
Following is the list :
values_list = ['apple', 87, 'fan', 88, 'jackal', 89, 'bat', 98, 'car', 84, 'ice', 80, 'car', 86, 'apple', 82, 'goat', 80, 'dog', 81, 'cat', 80, 'eagle', 90, 'eagle', 98, 'hawk', 89, 'dog', 79, 'fan', 89, 'goat', 85, 'car', 81, 'hawk', 90, 'ice', 85, 'cat', 78, 'goat', 84, 'jackal', 90, 'apple', 80, 'ice', 87, 'bat', 94, 'bat', 92, 'jackal', 91, 'eagle', 93, 'fan', 85]
following is the python script written to do the task :
for i in range(0,length(values_list),2):
value_count_dict = {values_list[i] : values_list[i+1]}
print(value_count_dict)
values_count_dict = dict(value_count_dict)
print(values_count_dict)
output of the script :
But expecting a single dictionary with all key:value pairs in it.
Thank you in advance!
You've misspelled len as length.
The most Pythonic way of doing this is likely with a list comprehension and range using the step argument.
[{values_list[i]: values_list[i+1]} for i in range(0, len(values_list), 2)]
# [{'apple': 87}, {'fan': 88}, {'jackal': 89}, {'bat': 98}, {'car': 84}, {'ice': 80}, {'car': 86}, {'apple': 82}, {'goat': 80}, {'dog': 81}, {'cat': 80}, {'eagle': 90}, {'eagle': 98}, {'hawk': 89}, {'dog': 79}, {'fan': 89}, {'goat': 85}, {'car': 81}, {'hawk': 90}, {'ice': 85}, {'cat': 78}, {'goat': 84}, {'jackal': 90}, {'apple': 80}, {'ice': 87}, {'bat': 94}, {'bat': 92}, {'jackal': 91}, {'eagle': 93}, {'fan': 85}]
In your code you create a new dictionary on each iteration, but you don't store them anywhere, so value_count_dict at the end of the loop is just the last pair.
value_counts = []
for i in range(0, len(values_list), 2):
value_count_dict = {values_list[i]: values_list[i+1]}
print(value_count_dict)
value_counts.append(value_count_dict)
Here we made a for loop that starts at 0 and ends at length of our list and the step is set to 2 because we can find the next key of our dictionary 2 step ahead. We have our key at x and the value at x+1 index of our list respectively. We have updated the key and value in the initially created empty dictionary.
values_list = ['apple', 87, 'fan', 88, 'jackal', 89, 'bat', 98, 'car', 84, 'ice', 80, 'car', 86, 'apple', 82, 'goat', 80, 'dog', 81, 'cat', 80, 'eagle', 90, 'eagle', 98, 'hawk', 89, 'dog', 79, 'fan', 89, 'goat', 85, 'car', 81, 'hawk', 90, 'ice', 85, 'cat', 78, 'goat', 84, 'jackal', 90, 'apple', 80, 'ice', 87, 'bat', 94, 'bat', 92, 'jackal', 91, 'eagle', 93, 'fan', 85]
final_dict={}
for x in range(0,len(values_list),2):
final_dict[values_list[x]]=values_list[x+1]
print(final_dict)
Try zip:
dct = dict(
zip(
values_list[0::2],
values_list[1::2],
)
)
For duplicate keys in your list, the last value will be taken.
You cannot have a duplicated keys as mentioned in above comments but you may try to have the values as list for the duplicated keys such as:
result = {}
l=values_list
for i in range(0, len(l), 2):
result.setdefault(l[i], []).append(l[i+1])
print(result)
and your output would look like:
{'apple': [87, 82, 80], 'fan': [88, 89, 85], 'jackal': [89, 90, 91], 'bat': [98, 94, 92], 'car': [84, 86, 81], 'ice': [80, 85, 87], 'goat': [80, 85, 84], 'dog': [81, 79], 'cat': [80, 78], 'eagle': [90, 98, 93], 'hawk': [89, 90]}
Related
How can I get the average marks for each student from following dataframe using Pandas groupby() and mean() methods?
The aim is to get the average marks in ascending order of all students.
import pandas as pd
# Marks of students in class 4A and 4B
data = {
'S4A': {
'Name': ['Amy', 'Mandy', 'Daisy', 'Ben', 'Peter', 'John'],
'Maths': [99, 87, 88, 70, 88, 76],
'Chemistry': [89, 90, 90, 90, 89, 82],
'Physics': [79, 97, 68, 80, 72, 95],
'English': [90, 65, 56, 67, 86, 82],
'Biology': [79, 89, 59, 70, 79, 78],
'History': [75, 81, 78, 55, 68, 84]
},
'S4B': {
'Name': ['Allen', 'Gordon', 'Jimmy', 'Nancy', 'Sammy', 'William'],
'Maths': [90, 86, 88, 80, 85, 86],
'Chemistry': [89, 78, 88, 90, 79, 82],
'Physics': [89, 97, 78, 81, 82, 55],
'English': [80, 85, 86, 77, 86, 82],
'Biology': [75, 89, 69, 70, 79, 78],
'History': [79, 81, 80, 65, 68, 84]
}
}
# list of subjects
subjects = ['Maths', 'Chemistry', 'Physics', 'English', 'Biology', 'History']
# create dataframe
df = pd.DataFrame(data)
You need to create a dataframe for each class and then compute mean or concat all the classes and compute mean.
df = pd.concat([pd.DataFrame(data[k]) for k in data], ignore_index=True)
mean_df = df.set_index('Name').mean(1)
print(mean_df)
Name
Amy 85.166667
Mandy 84.833333
Daisy 73.166667
Ben 72.000000
Peter 80.333333
John 82.833333
Allen 83.666667
Gordon 86.000000
Jimmy 81.500000
Nancy 77.166667
Sammy 79.833333
William 77.833333
dtype: float64
I have this dict:
{'q1': [5, 6, 90, 91, 119, 144, 181, 399],
'q2': [236, 166],
'q3': [552, 401, 1297, 1296],
}
And I'd like to prepend a 'd' to every element within each value's list:
{'q1': ['d5', 'd6', 'd90', 'd91', 'd119', 'd144', 'd181', 'd399'],
'q2': ['d236', 'd166'],
'q3': ['d552', 'd401', 'd1297', 'd1296'],
}
I have tried out = {k: 'd'+str(v) for k,v in out.items()} but this only adds the 'd' to the outside of each value's list:
{'q1': d[5, 6, 90, 91, 119, 144, 181, 399],
'q2': d[236, 166],
'q3': d[552, 401, 1297, 1296],
}
I imagine I have to do a sort of list comprehension within the dict comprehension, but I am not sure how to implement.
Try:
dct = {
"q1": [5, 6, 90, 91, 119, 144, 181, 399],
"q2": [236, 166],
"q3": [552, 401, 1297, 1296],
}
for v in dct.values():
v[:] = (f"d{i}" for i in v)
print(dct)
Prints:
{
"q1": ["d5", "d6", "d90", "d91", "d119", "d144", "d181", "d399"],
"q2": ["d236", "d166"],
"q3": ["d552", "d401", "d1297", "d1296"],
}
Try using an f-string in a nested comprehension if you desire to keep your original dict unchanged:
>>> d = {'q1': [5, 6, 90, 91, 119, 144, 181, 399], 'q2': [236, 166], 'q3': [552, 401, 1297, 1296]}
>>> {k: [f'd{x}' for x in v] for k, v in d.items()}
{'q1': ['d5', 'd6', 'd90', 'd91', 'd119', 'd144', 'd181', 'd399'], 'q2': ['d236', 'd166'], 'q3': ['d552', 'd401', 'd1297', 'd1296']}
What is the difference between studentsDict.values() and studentsDict[key].values in the following code?
studentsDict = {'Ayush': {'maths': 24, 'english': 19, 'hindi': 97, 'bio': 20, 'science': 0}, 'Pankaj': {'maths': 52, 'english': 76, 'hindi': 68, 'bio': 97, 'science': 66}, 'Raj': {'maths': 85, 'english': 79, 'hindi': 51, 'bio': 36, 'science': 75}, 'iC5z4DK': {'maths': 24, 'english': 92, 'hindi': 31, 'bio': 29, 'science': 91}, 'Zf1WSV6': {'maths': 81, 'english': 58, 'hindi': 85, 'bio': 31, 'science': 7}}
for key in studentsDict.keys():
for marks in studentsDict[key].values():
if marks < 33:
print(key, "FAILED")
break
studentsDict.keys() gives you each of the keys in the outer dict: "Ayush", "Pankaj", "Raj", "iC5z4DK" and "Zf1WSV6".
studentsDict[key].values() gives you the values for the entry in studentsDict corresponding to key. For example, if key is "Ayush", you would get 24, 19, 97, 20, and 0.
I have one dictionary with 2 separate key-value pairs and I want to merge them into 1 list with separate dictionaries for all key-value pairs.
Example Input:
{'Boys': [72, 68, 70, 69, 74], 'Girls': [63, 65, 69, 62, 61]}
Example Output:
[{'Boys': 72,'Girls': 63}, {'Boys': 68, 'Girls': 65}, {'Boys': 70, 'Girls': 69}, {'Boys': 69, 'Girls': 62}, {‘Boys’:74,'‘Girls':61]
I tried looping over the dictionary but I was unable to create a single list out of it.
Any help is appreciated. Thanks in advance
my_dict = {'Boys': [72, 68, 70, 69, 74], 'Girls': [63, 65, 69, 62, 61]}
new = [{'Boys': x, 'Girls': y} for x, y in zip(my_dict['Boys'], my_dict['Girls'])]
print(new)
[{'Boys': 72, 'Girls': 63}, {'Boys': 68, 'Girls': 65}, {'Boys': 70, 'Girls': 69}, {'Boys': 69, 'Girls': 62}, {'Boys': 74, 'Girls': 61}]
Or a simpler version:
new = []
for boy, girl in zip(my_dict['Boys'], my_dict['Girls']):
new.append({'Boys': boy, 'Girls': girl})
Try this:
dict1={'Boys': [72, 68, 70, 69, 74], 'Girls': [63, 65, 69, 62, 61]}
list1=[{'Boys':i,'Girls':j} for i,j in zip(dict1['Boys'],dict1['Girls'])]
print(list1)
Try:
dt = {'Boys': [72, 68, 70, 69, 74], 'Girls': [63, 65, 69, 62, 61]}
out = [dict(zip(dt.keys(), x)) for x in zip(*dt.values())]
print(out)
I have two lists:
names: ['Mary', 'Jack', 'Rose', 'Mary', 'Carl', 'Fred', 'Meg', 'Phil', 'Carl', 'Jack', 'Fred', 'Mary', 'Phil', 'Jack', 'Mary', 'Fred', 'Meg']
grades: [80, 88, 53, 80, 64, 61, 75, 80, 91, 82, 68, 76, 95, 58, 89, 51, 81, 78]
I want to be able to take the average of each persons test scores. For example, Mary pops up in the names list 4 times and I want to be able to take the test scores that are mapped to her and take that average.
The issue is how to compare the duplicate names with the test scores.
Note: I do know that the grades list is longer than the names list, but this was the two lists that was given to me.
Here is what I have done so far
def average_grades(names, grades):
averages = dict()
name_counter = 0
for name in names:
# if the name is the same
if name == names:
# count the occurence of the name
name_counter += 1
print(name_counter)
# cycle through the grades
# for grade in grades:
# print(grade)
Here's a way:
from collections import defaultdict, Counter
names = ['Mary', 'Jack', 'Rose', 'Mary', 'Carl', 'Fred', 'Meg', 'Phil', 'Carl', 'Jack', 'Fred', 'Mary', 'Phil', 'Jack', 'Mary', 'Fred', 'Meg']
grades = [80, 88, 53, 80, 64, 61, 75, 80, 91, 82, 68, 76, 95, 58, 89, 51, 81, 78]
score = defaultdict(int)
# this line initializes a default dict with default value = 0
frequency = Counter(names)
# this yields: Counter({'Mary': 4, 'Jack': 3, 'Fred': 3, 'Carl': 2, 'Meg': 2,'Phil': 2, 'Rose': 1})
for name, grade in zip(names, grades):
score[name] = score.get(name,0)+(grade / frequency[name])
# here you add the (grade of name / count of name) to each name,
# score.get(name,0) this line adds a default value 0 if the key does not exist already
print(score)
Output:
defaultdict(<class 'int'>, {'Mary': 81.25, 'Jack': 76.0, 'Rose': 53.0, 'Carl': 77.5, 'Fred': 60.0, 'Meg': 78.0, 'Phil': 87.5})
NOTE: It ignores the last grade, as I have no idea what to do with it.
You can iterate in parallel, find their average and add to the dictionary:
from itertools import groupby
from collections import defaultdict
names = ['Mary', 'Jack', 'Rose', 'Mary', 'Carl', 'Fred', 'Meg', 'Phil', 'Carl', 'Jack', 'Fred', 'Mary', 'Phil', 'Jack', 'Mary', 'Fred', 'Meg']
grades = [80, 88, 53, 80, 64, 61, 75, 80, 91, 82, 68, 76, 95, 58, 89, 51, 81, 78]
d = defaultdict(int)
f = lambda x: x[0]
for k, g in groupby(sorted(zip(names, grades), key=f), key=f):
grp = list(g)
d[k] = sum(x[1] for x in grp) / len(grp)
print(d)