Costa.Gustavo
Costa.Gustavo

Reputation: 849

Python: Different types of dictionary key data

Given a dictionary like the one below:

dic = {1:10, 2:20, 3:30, 'A': 10, 'B': 20, 'C':30}

How can I calculate the mean values ​​of int keys and string keys separately?

Upvotes: 0

Views: 91

Answers (4)

LiuXiMin
LiuXiMin

Reputation: 1265

Want to introduce one not so common way:

from operator import itemgetter
from statistics import mean
from itertools import groupby

dic = {1:10, 2:20, 3:30, 'A': 10, 'B': 20, 'C':30}
[mean(itemgetter(*g)(dic)) for _, g in groupby(dic, key=lambda k: isinstance(k, int))]
# [20, 20]

or

{k: mean(itemgetter(*g)(dic)) for k, g in groupby(dic, key=lambda i: type(i))}
# {int: 20, str: 20}

possible overhead, but very suitable. And, the three helper are interesting :-)

Upvotes: 2

Yash89
Yash89

Reputation: 71

What does the values of string keys mean? if they are single character keys I assume you want to calculate the ASCI value of the keys. If that is the case here is code to do that

dic = {1:10, 2:20, 3:30, 'A': 10, 'B': 20, 'C':30
total_int = 0
total_str = 0
count_int = 0
count_str = 0
for keys,values in dic.items():
    if type(keys) is int : #checking the key is int 
        count_int +=  1
        total_int += keys
     elif type(keys) is str: 
        count_str +=  1
        total_str += ord(keys)

print total_int/count_int # will print int avg
print total_str/count_str # will print str avg

Upvotes: 2

Omer Tekbiyik
Omer Tekbiyik

Reputation: 4744

You need to check if keys is int and calculate the mean :

dic = {1:10, 2:20, 3:30, 'A': 10, 'B': 20, 'C':30}


total_int = 0
count_str = 0
total_str = 0
count_int = 0
for keys,values in dic.items():

if type(keys) is int :
    count_int = count_int + 1
    total_int = total_int + values
    print (values)

elif type(keys) is str :
    count_str = count_str + 1
    total_str = total_str + values


print (total_int/count_int)
print (total_str/count_str)

Upvotes: 1

Paul Joireman
Paul Joireman

Reputation: 2835

I think (?) the OP wants the mean of the values of integer keyed items and also a separate mean of the string keyed items. Here is an alternate option:

 dic = {1:10, 2:20, 3:30, 'A': 10, 'B': 20, 'C':30}

 int_keyed_values = [v for k,v in dic.items() if type(k) is int]
 str_keyed_values = [v for k,v in dic.items() if type(k) is str]

 int_mean = sum(int_keyed_values)/len(int_keyed_values)
 str_mean = sum(str_keyed_values)/len(str_keyed_values)

Upvotes: 2

Related Questions