dictionary = {'Alex': [1,2,3], 'Tim': [4,5,6], ' Sally': [7,8,9]}
What I want is to draw a table having the names in the first line and the grades under each name, and I want it to be dynamic. Basically I won't have to interfere in anyway with the content in the dictionary (as in precise an exact name) just read every key in it.
I tried the following:
for x in range(size):
table.append(dictionary[x])
table.append(int(100 - 100 * dictionary[x] / B),)
for x in range (size*2+2):
values.append(np.array(np.array(table[1:])[:, x+1],dtype=np.float32))
Note that 100 exists because in the actual code the numbers are basically being used to get a percentage divided by B
, and in the size*2+2
because I'm adding other characters but that won't matter in this question I'm asking.
(Running a python2.7)
So this sounds like a homework question... I am going to give you some help but you will need to put in some work as well.
Here is the way to make a table where the first row prints the name of each person and under the name will be a grade for that student. (Python 3.6)
dictionary = {'Alex': [1,2,3], 'Tim': [4,5,6], 'Sally': [7,8,9]}
print("%s" % dictionary)
# print the names of the students
for key in dictionary:
print("%s" % ('{0:%ds}' % (len(key) + 2)).format(key), end="")
print()
# print the grades under each student
i = 0
keys = list(dictionary.keys())
while i < len(keys):
j = 0
while j < len(keys):
values = list(dictionary.values())
print("%s " % ('{0:%dd}' % (len(keys[j]))).format(values[j][i]), end="")
j = j + 1
print()
i = i + 1
Output:
{'Alex': [1, 2, 3], 'Tim': [4, 5, 6], 'Sally': [7, 8, 9]}
Alex Tim Sally
1 4 7
2 5 8
3 6 9
Hope this helps
As @Dadep said in the comment, you can load your dictionary into the pandas DataFrame this way:
import pandas as pd
import numpy as np
dictionary = {'Alex': [1,2,3], 'Tim': [4,5,6], 'Sally': [7,8,9]}
df = pd.DataFrame.from_dict(dictionary)
DataFrame is a table and you can perform operations over it's columns. The one we created looks like this if you print it:
Alex Sally Tim
0 1 7 4
1 2 8 5
2 3 9 6
I am not sure, what operation you want to perform, but I will give you an example how you can add a column or edit one:
B = 10
df["Alex"] = (100 - 100 * df["Alex"] / B).apply(np.int64) # Edit Alex column
df["Sally2"] = (100 - 100 * df["Sally"] / B).apply(np.int64) # Make new Sally2 column
Then the table looks like this:
Alex Sally Tim Sally2
0 90 7 4 30
1 80 8 5 20
2 70 9 6 10
Note that if you will use pandas, all columns need to have same length.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.