bajro
bajro

Reputation: 1250

Python get value from index of list

Let's say I have a dict with the keys 1, 2, 3, 4 and the values are lists, e.g.:

{1: ['myMoney is 335', 'jeff', 'Manchester'],
 2: ['myMoney is 420', 'jeff', 'Birmingham']}

I want to create a function which is taking ONLY the value from the first index in the list of every key and making a sum of them. Is there any possibility to "filter" only the value out of this index for every key?

Upvotes: 1

Views: 3131

Answers (5)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You can rsplit the first string once on whitespace and get the second element casting to int and sum:

print(sum(int(val[0].rsplit(None,1)[1]) for val in d.itervalues()))

A better approach might be to have a dict of dicts and access the item you want by key:

d = {1: {"myMoney":335, "name":"jeff","city":"Manchester"}, 2:{"myMoney":420, "name":"jeff", "city":"Birmingham"}}

print(sum(dct["myMoney"] for dct in d.itervalues()))
755

Upvotes: 0

Mike Müller
Mike Müller

Reputation: 85442

Splitting it is more stable if the string 'myMoney is ' changes later:

 d = {1: ['myMoney is 335', 'jeff', 'Manchester'], 
      2:['myMoney is 420', 'jeff', 'Birmingham']}
sum(float(value[0].split()[-1]) for value in d.values())

d.values() gives you all the values. No need for the keys here. 'myMoney is 335’.split() splits the string at white spaces. We take the last entry, i.e. the number, with the index -1. float() converts a string into a number. Finally, sum() gives you the sum.

Upvotes: 3

o17t H1H' S'k
o17t H1H' S'k

Reputation: 2744

d = {1: ["myMoney is 335", "Jeff", "Manchester"], 2: ["myMoney is 420", "Jeff", "Birmingham"]}

sum(float(v[0][11:]) for v in d.values())

Upvotes: 0

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23213

d = {1: ['myMoney is 335', 'jeff', 'Manchester'], 2:['myMoney is 420', 'jeff', 'Birmingham']}

def get_filtered(d):
    if not d:
        return {}
    return {k: int(v[0][len("myMoney is "):])
            for k,v in d.iteritems()}

assert get_filtered(d) == {1: 335, 2: 420}
summed_up = sum(get_filtered(d).itervalues())
assert summed_up == 755

Upvotes: 0

Simon Brix
Simon Brix

Reputation: 102

If you just want to get the first value in your list of every key, you'd just need to do something like:

d[key][list_index]

So a function would look like:

d = {1: ["myMoney is 335", "Jeff", "Manchester"], 2: ["myMoney is 420", "Jeff", "Birmingham"]}

def firstValueSum(d):
    sum = 0
    for item in d:
        sum += int(d[item][0][11:])
    return sum

print firstValueSum(d)

Upvotes: 0

Related Questions