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?
5 Answers 5
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.
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)
-
yeah thats pretty sweet how you would do it, but you cant just remove the string "myMones is"....so my problem is i have the String "myMoney is 335" in the first index of the list AND i want only the value to get out of this index!bajro– bajro2015年05月10日 11:35:30 +00:00Commented May 10, 2015 at 11:35
-
Oh, sorry. I misunderstood you a bit there. In that case you can use string slicing to ignore the first 11 characters (myMoney is) from each index. See my edited answer above :-)Simon Brix– Simon Brix2015年05月10日 11:42:22 +00:00Commented May 10, 2015 at 11:42
-
oh wow nice thank you for your help!! helped me a lot, i hope so :)bajro– bajro2015年05月10日 11:50:34 +00:00Commented May 10, 2015 at 11:50
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
d = ...
line so we don't have to guess what you might mean. Right now it's just full of errors.