简体   繁体   中英

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, eg:

{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?

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, ie the number, with the index -1 . float() converts a string into a number. Finally, sum() gives you the sum.

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)
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
d = {1: ["myMoney is 335", "Jeff", "Manchester"], 2: ["myMoney is 420", "Jeff", "Birmingham"]}

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

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

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