Reputation: 1250
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
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
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
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
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
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