简体   繁体   中英

How to append key and value (list) to new dictionary?

This program is supposed to compute two descriptive statistics of the grades associates with each key in the all_grades dictionary. Creates a new dictionary that has the same keys as all_grades, but the values are a tuple with the two stats.

The two stats are: mean and median

all_grades: dictionary of grades with the following keys and values

key: alphabetic string, student first name

value: list of non-negative integers (student grades)

Returns: dictionary of grade stats (I'm using an empty dict "average_grades")

key: alphabetic string, student first name (same as key in all_grades) value: decimal - average of grades in the input parameter

THE GOAL: all_grades({'ann': [70, 90, 100], 'bob': [75, 95]}) will return {'ann': (86.6, 90.0), 'bob': (85.0, 85.0)}

I'm able to parse through all_grades and get the median and mean of the list, but am having trouble appending the key as well as the tuple to the new list.

What I have so far:

average_grades = {}

    for key, val in all_grades.items():
            x = statistics.mean(val)
            y = statistics.median(val)
            average_grades.append(key, x, y)
            print(average_grades)

i think you want

average_grades = {}

for key, val in all_grades.items():
    x = statistics.mean(val)
    y = statistics.median(val)
    average_grades[key]=[x,y]
print(average_grades)

You can use dict comprehension.

Note : All you needed was using average_grades.update({key: [x, y]}) instead of append since, you did not have the key present in the dict already.

Solution

As a generic example, if you have some keys and values, you can create a dictionary using a dict comprehension in a single line.

dict((key, val) for key, val in zip(keys, vals))

The one line dict comprehension in your case would look like this:

dict((key, [statistics.mean(val), statistics.median(val)]) for key, val in all_grades.items())

Solution In Detail

keys = list('abcdef')
vals = np.arange(6).tolist()
print('keys: {}'.format(keys))
print('vals: {}'.format(vals))
d = dict((key, val) for key, val in zip(keys, vals))
print('Dict: \n{}'.format(d))

Output :

keys: ['a', 'b', 'c', 'd', 'e', 'f']
vals: [0, 1, 2, 3, 4, 5]
Dict: 
{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5}

Correction to Your Code

All you needed was using average_grades.update({key: [x, y]}) instead of append since, you did not have the key present in the dict already.

average_grades = {}

for key, val in all_grades.items():
    x = statistics.mean(val)
    y = statistics.median(val)
    average_grades.update({key: [x, y]})
print(average_grades)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM