1

I have a dictionary whereas the values are of string type. But I want to calculate the average per key whereas the empty string is a missing value. Here's my code just need a small twerk for it to work...with error : int() argument must be a string or a number, not 'list'

dic = {'E': ['1', '', '3'], 'M': ['2', '', '1']}
for k,n in dic.items():
    k = [0]
    n = [1]

D = {k: (int(n)) for k, n in dic.items() if n}
ave = {k:sum(D)/float(len(D))} if D else '-'
print ave

Expected output: {'E': 2, 'M': 1.5}

  • Values of your dictionary are **not** strings, they are lists of strings. If I understand your problem correctly (of that I am not sure), your expected result is `{'E': 2.0, 'M': 1.5}`, is that right? – Błotosmętek Aug 18 '17 at 09:31
  • Yes, list of strings. – user8459844 Aug 18 '17 at 09:51
  • @Ashwini This does not look at all like a dupe. The OP obviously knows how to iterate over a dictionary. – Sven Marnach Aug 18 '17 at 10:11
  • @SvenMarnach [Not really.](https://stackoverflow.com/posts/45753125/revisions) – Ashwini Chaudhary Aug 18 '17 at 10:12
  • @AshwiniChaudhary I see. Still, that's only part of the problem. – Sven Marnach Aug 18 '17 at 10:13
  • @user8459844 You should solve this problem bottom-up: First implement a function to compute the average of a list of number strings, then apply that function to all the lists in a dictionary. – Sven Marnach Aug 18 '17 at 10:15
  • @SvenMarnach yes I tried on a list of strings and it worked but now I don't know how it could work for list of strings in a dictionary... – user8459844 Aug 18 '17 at 10:23
  • @user8459844 You iterate over the dictionary, and apply the function to each value, e.g. `{k: average(v) for k, v in dic.items()}`, where `average()` is the function to compute the average for a single list. – Sven Marnach Aug 18 '17 at 11:01

1 Answers1

0
dic = {'E': ['1', '', '3'], 'M': ['2', '', '1']}
ave = dict()
for k in dic:
   nonempty = [ float(v) for v in dic[k] if v != '' ]
   ave[k] = sum(nonempty) / len(nonempty)
print ave
Błotosmętek
  • 12,717
  • 19
  • 29