Given the following data how can I create a dictionary where the keys are the names of the students, and the values are dictionaries where the key is the test and it´s value is the grade they got in it.
grades = [
['Students', 'Test 1', 'Test 2', 'Test 3'],
['Tomas', '100', '90', '80'],
['Marcos', '88', '99', '111'],
['Flavia', '45', '56', '67'],
['Ramon', '59', '61', '67'],
['Ursula', '73', '79', '83'],
['Federico', '89', '97', '101']
]
I tried doing this, but I don´t know why it´s not showing the grades correctly.
notas_dict={}
def dic(etiquets, notas):
for i in range(len(etiquets)):
notas_dict[etiquets[i]]=int(notas[i])
return notas_dict
dic(['Test 1','Test 2', 'Test 3'], ['100','80','90'] )
dic_final={}
for line in grades[1:]:
line_grades=[int(element) for element in line[1:]]
dic_final[line[0]]=dic(['Test 1','Test 2', 'Test 3'], line_grades)
print(dic_final)
The output should be :
{'Tomas': {'Test 1': 100, 'Test 2': 90, 'Test 3': 80}, 'Marcos': {'Test 1': 88, 'Test 2': 99, 'Test 3': 111}, 'Flavia': {'Test 1': 45, 'Test 2': 56, 'Test 3': 67}, 'Ramon': {'Test 1': 59, 'Test 2': 61, 'Test 3': 67}, 'Ursula': {'Test 1': 73, 'Test 2': 79, 'Test 3': 83}, 'Federico': {'Test 1': 89, 'Test 2': 97, 'Test 3': 101}}
You can use:
{i[0]:dict(zip(grades[0][1:],i[1:])) for i in grades[1:]}
results in:
{'Tomas': {'Test 1': '100', 'Test 2': '90', 'Test 3': '80'},
'Marcos': {'Test 1': '88', 'Test 2': '99', 'Test 3': '111'},
'Flavia': {'Test 1': '45', 'Test 2': '56', 'Test 3': '67'},
'Ramon': {'Test 1': '59', 'Test 2': '61', 'Test 3': '67'},
'Ursula': {'Test 1': '73', 'Test 2': '79', 'Test 3': '83'},
'Federico': {'Test 1': '89', 'Test 2': '97', 'Test 3': '101'}}
If you want to get grades as int:
{i[0]:dict(zip(grades[0][1:],list(map(int,i[1:])))) for i in grades[1:]}
create a dataframe then use to_records to create a list of tuples where each tuple is a row. You can then slice the tuple by index.
grades = [
['Students', 'Test 1', 'Test 2', 'Test 3'],
['Tomas', '100', '90', '80'],
['Marcos', '88', '99', '111'],
['Flavia', '45', '56', '67'],
['Ramon', '59', '61', '67'],
['Ursula', '73', '79', '83'],
['Federico', '89', '97', '101']
]
Columns=grades[0]
df=pd.DataFrame(columns=Columns)
for i in range(1, len(grades)):
df_length = len(df)
df.loc[df_length] = grades[i]
print(df.to_records())
output:
[(0, 'Tomas', '100', '90', '80') (1, 'Marcos', '88', '99', '111')
(2, 'Flavia', '45', '56', '67') (3, 'Ramon', '59', '61', '67')
(4, 'Ursula', '73', '79', '83') (5, 'Federico', '89', '97', '101')]
or
dict=df.T.to_dict()
for k,v in dict.items():
print(k,v['Students'],v['Test1'],v['Test2'],v['Test3'])
Related
I have the following nested list:
orders = [['Large', 'Latte', 2.45],
['',
'Frappes - Coffee',
2.75,
'',
'Cortado',
2.05,
'',
'Glass of milk',
0.7,
'',
'Speciality Tea - Camomile',
1.3,
'',
'Speciality Tea - Camomile',
1.3]]
Each inner list is n elements long, but always divisible by 3.
My issue is that I am trying to return a list of dictionaries by iterating through orders with the following:
[dict(size=i[0],product=i[1],price=i[2]) for i in orders]
However, that only returns the first element inside products[1]
returns [{'size': 'Large', 'product': 'Latte', 'price': 2.45},
{'size': '', 'product': 'Frappes - Coffee', 'price': 2.75}]
I tried doing a second loop but that also doesn't work.
I want my code to output the following:
[
[{'size': 'Large', 'product': 'Latte', 'price': 2.45}],
[{'size': '', 'product': 'Frappes - Coffee', 'price': 2.75},
{'size': '', 'product': 'Cortado', 'price': 2.05},
{'size': '', 'product': 'Glass of Milk', 'price': 0.7},
{'size': '', 'product': 'Speciality Tea - Camomile', 'price': 1.3},
{'size': '', 'product': 'Speciality Tea - Camomile', 'price': 1.3}]
]
If anyone could point me in the right direction it would be much appreciated!
You can iterate the sublists as chunk of size 3 and then make dict:
def chunks(lst, n):
"""Yield successive n-sized chunks from lst.
https://stackoverflow.com/questions/312443/how-do-you-split-a-
list-into-evenly-sized-chunks
"""
for i in range(0, len(lst), n):
yield lst[i:i + n]
[[dict(size=i[0],product=i[1],price=i[2])
for i in chunks(order, 3)]
for order in orders]
Output:
[[{'size': 'Large', 'product': 'Latte', 'price': 2.45}],
[{'size': '', 'product': 'Frappes - Coffee', 'price': 2.75},
{'size': '', 'product': 'Cortado', 'price': 2.05},
{'size': '', 'product': 'Glass of milk', 'price': 0.7},
{'size': '', 'product': 'Speciality Tea - Camomile', 'price': 1.3},
{'size': '', 'product': 'Speciality Tea - Camomile', 'price': 1.3}]]
The problem is orders is inconsistent. Fix it by changing it to make each new order a list would be the best solution
orders = [
["Large", "Latte", 2.45],
["", "Frappes - Coffee", 2.75],
["", "Cortado", 2.05],
["", "Glass of milk", 0.7],
["","Speciality Tea - Camomile",1.3],
["","Speciality Tea - Camomile",1.3]
]
{'fname': 'viji', 'lname': 'vikki', 'adrress1': '1700', 'address2': '21st Ave W.', 'city': 'Florida', 'state': [], 'pin': '34205', 'phone': '(941) 748-4104', 'email': '', 'designation': 'Assisted Living Facility, Skilled Nursing Facility'}
{'fname': 'Amy', 'lname': 'Hanna-Eckenrode', 'adrress1': '1700', 'address2': '21st Ave W.', 'city': 'Florida', 'state': [], 'pin': '34205', 'phone': '(941) 748-4104', 'email': '', 'designation': 'Assisted Living Facility, Skilled Nursing Facility'}
i have dictionary like this, but i want make this as like
[
{'fname': 'viji', 'lname': 'vikki', 'adrress1': '1700', 'address2': '21st Ave W.', 'city': 'Florida', 'state': [], 'pin': '34205', 'phone': '(941) 748-4104', 'email': '', 'designation': 'Assisted Living Facility, Skilled Nursing Facility'},
{'fname': 'Amy', 'lname': 'Hanna-Eckenrode', 'adrress1': '1700', 'address2': '21st Ave W.', 'city': 'Florida', 'state': [], 'pin': '34205', 'phone': '(941) 748-4104', 'email': '', 'designation': 'Assisted Living Facility, Skilled Nursing Facility'}
]
looking for aid from other developer, any help will be usefull for me,thanks
In the third code snippet, you already have it set properly.
stuff = [{"foo": "bar'd"}, {"money": 0}]
If you want to add more dictionaries to the list, then the .append method with a variable as a parameter does just fine.
stuff = [{"foo": "bar'd"}]
sad = {"money": 0}
stuff.append(sad)
print(stuff)
> [{"foo": "bar'd"}, {"money": 0}]
If you want to append dict() objects to list() objects, you can simply use append() method.
For example,
dict1 = {'fname': 'viji', 'lname': 'vikki'}
dict2 = {'fname': 'Amy','lname': 'Hanna-Eckenrode'}
lst = []
lst.append(dict1)
lst.append(dict2)
print(lst)
Now lst will be
[{'fname': 'viji', 'lname': 'vikki'}, {'fname': 'Amy', 'lname': 'Hanna-Eckenrode'}]
I have a table like below, stored in a dictionary:
The dictionary looks like this
d = {
'A': ['45', '70', '5', '88', '93', '79', '87', '69'],
'B': ['99', '18', '91', '3', '92', '2', '67', '15'],
'C': ['199200128', '889172415', '221388292', '199200128', '889172415', '889172415', '199200128', '221388292'],
'D': ['10:27:05', '07:10:29', '17:04:48', '10:25:42', '07:11:18', '07:11:37', '10:38:11', '17:08:55'],
'E': ['73', '6', '95', '21', '29', '15', '99', '9']
}
I'd like to sort the dictionary based on the hours from lowest to highest and sum the columns A, B and E corresponding the same value in column C as in image below (where sums of A, B and E are in red):
Then, the resulting dictionary would look like this:
{
'A': ['70', '93', '79', '242', '88', '45', '133', '87', '5', '69', '161'],
'B': ['18', '92', '2', '112', '3', '99', '102', '67', '91', '15', '173'],
'C': ['889172415', '889172415', '889172415', '', '199200128', '199200128', '', '199200128', '221388292', '221388292', ''],
'D': ['07:10:29', '07:11:18', '07:11:37', '', '10:25:42', '10:27:05', '', '10:38:11', '17:04:48', '17:08:55', ''],
'E': ['6', '29', '15', '50', '21', '73', '94', '99', '95', '9', '203']
}
I currently try to sort the input dictionary with this code, but doesn´t seem to work for me.
>>> sorted(d.items(), key=lambda e: e[1][4])
[
('D', ['10:27:05', '07:10:29', '17:04:48', '10:25:42', '07:11:18', '07:11:37', '10:38:11', '17:08:55']),
('E', ['73', '6', '95', '21', '29', '15', '99', '9']),
('C', ['199200128', '889172415', '221388292', '199200128', '889172415', '889172415', '199200128', '221388292']),
('B', ['99', '18', '91', '3', '92', '2', '67', '15']),
('A', ['45', '70', '5', '88', '93', '79', '87', '69'])
]
>>>
May someone give some help with this. Thanks
Do you allow to use pandas to solve this task ?
If yes, then you can transform your data to
pd.DataFrame
object
data = pd.DataFrame.from_dict(dictionary, orient = 'columns')
data = data.sort_values(by =„D”)
And then return to dictionary again using
_dict = data.to_dict()
I'm trying to make a single dictionary from 3 lists one being a nested list.
Companies = ['Company A', 'Company B']
features = ['Feature 1', 'Feature 2', 'Feature 3']
values = [['On', 'Off', 'On'], ['Off', 'On', 'Off']]
# This is what i would like the out put to look like, any help would be great
results = {{'Company A': {'Feature 1' : 'On', 'Feature 2': 'Off', 'Feature
3': 'On'}, 'Company B': {'Feature 1' : 'Off', 'Feature 2': 'On', 'Feature
3': 'Off'}}}
Companies = ['Company A', 'Company B']
features = ['Feature 1', 'Feature 2', 'Feature 3']
values = [['On', 'Off', 'On'], ['Off', 'On', 'Off']]
results = {}
for i in range(len(Companies)):
results[Companies[i]] = dict(zip(features,values[i]))
print (results)
Output:
{'Company A': {'Feature 3': 'On', 'Feature 2': 'Off', 'Feature 1': 'On'}, 'Company B': {'Feature 3': 'Off', 'Feature 2': 'On', 'Feature 1': 'Off'}}
You can use a dict comprehension:
results = {comp: {feat: v for feat,v in zip(features,val)} for comp,val in zip(Companies,values)}
Output:
{'Company A': {'Feature 1': 'On', 'Feature 2': 'Off', 'Feature 3': 'On'}, 'Company B': {'Feature 1': 'Off', 'Feature 2': 'On', 'Feature 3': 'Off'}}
I have a dataset that consists of thousands of entries such as the following:
[{'country': {'id': '1A', 'value': 'Arab World'},
'date': '2016',
'decimal': '0',
'indicator': {'id': 'SP.POP.TOTL', 'value': 'Population, total'},
'value': None},
{'country': {'id': '1A', 'value': 'Arab World'},
'date': '2015',
'decimal': '0',
'indicator': {'id': 'SP.POP.TOTL', 'value': 'Population, total'},
'value': '392168030'},
{'country': {'id': '1A', 'value': 'Arab World'},
'date': '2014',
'decimal': '0',
'indicator': {'id': 'SP.POP.TOTL', 'value': 'Population, total'},
'value': '384356146'},
....17020-ish rows later.....
{'country': {'id': 'XH', 'value': 'IDA blend'},
'date': '1960',
'decimal': '0',
'indicator': {'id': 'SP.POP.TOTL', 'value': 'Population, total'},
'value': '163861743'},
...]
I want to create a DataFrame using pandas such that y-axis = 'id' and x-axis = 'date', with 'value' being the stored value. I can't figure out the best way to approach this...
EDIT:
Imagine a sheet with just numbers ('value' from the dataset). The x-axis columns would be the extracted date and the y-axis rows would be the country id ('id'). The final object would be a dataset that is y*x in size. The numbers would all be of type 'float'.
EDIT 2:
The dataset represents ~304 countries from 1960 - 2016, so there are approximately 304 * 56 = 17024 entries in the dataset. I need to store the 'value' (where for entry 2, value = 392168030) with respect to each country and date.
EDIT 3:
Using the above data, an example output data set would be structured thusly:
2016 . 2015 . 2014 . ... 1960
1A . None . 392168030 384356146 . ... w
...
XH . x y z 163861743
First extract the information from origin dataset:
dataset = [{'country': {'id': '1A', 'value': 'Arab World'},
'date': '2016',
'decimal': '0',
'indicator': {'id': 'SP.POP.TOTL', 'value': 'Population, total'},
'value': None},
{'country': {'id': '1A', 'value': 'Arab World'},
'date': '2015',
'decimal': '0',
'indicator': {'id': 'SP.POP.TOTL', 'value': 'Population, total'},
'value': '392168030'},
{'country': {'id': '1A', 'value': 'Arab World'},
'date': '2014',
'decimal': '0',
'indicator': {'id': 'SP.POP.TOTL', 'value': 'Population, total'},
'value': '384356146'},
{'country': {'id': 'XH', 'value': 'IDA blend'},
'date': '1960',
'decimal': '0',
'indicator': {'id': 'SP.POP.TOTL', 'value': 'Population, total'},
'value': '163861743'}]
df = [[entry['country']['id'], entry['date'], entry['value']] for entry in dataset]
df = pd.DataFrame(df, columns=['id','date','value'])
Then pivot the datafrme:
df = df.pivot(index='id',columns='date',values='value')
The output:
date 1960 2014 2015 2016
id
1A None 384356146 392168030 None
XH 163861743 None None None
I had to make a guess about how the "thousands of entries" might look but I came up with this possible solution.
entry1 = {
'country': {'id': '1A', 'value': 'Arab World'},
'date': '2016',
'decimal': '0',
'indicator': {'id': 'SP.POP.TOTL', 'value': 'Population, total'},
'value': None
}
entry2 = {
'country': {'id': '1B', 'value': 'Another World'},
'date': '2016',
'decimal': '0',
'indicator': {'id': 'SP.POP.TOTL', 'value': 'Population, total'},
'value': None
}
entries = [entry1, entry2]
countries_index = []
date_cols = []
countries_index = []
date_cols = []
for entry in entries:
date_cols.append(entry['date'])
countries_index.append(entry['country']['id'])
import pandas as pd
df = pd.DataFrame(date_cols, columns=['date'], index=countries_index)
This creates a data frame,df which looks like this...
date
1A 2016
1B 2016