Mahsa
Mahsa

Reputation: 97

How to iterate over values in dictionary which each key has multiple values

I have a dictionary like this:

{4722: "['children', 'dance', 'education','technology', 'teaching']",
3200: "['alternative energy', 'sustainability', 'technology']",
1636: "['computers', 'performance', 'simplicity', 'software', 'ice']",
1697: "['MacArthur grant', 'inequality', 'technology', 'pollution']"}

Now I want to find the word 'technology' in each row and sum the keys. Like here I should have the sum of 4722 + 3200 + 1697 .

Can anyone help me please?

I should mention that my original data frame has 2000 rows.

Upvotes: 1

Views: 91

Answers (2)

Robᵩ
Robᵩ

Reputation: 168626

Use the sum() built-in function, passing an appropriate generator expression: sum(k for k,v in d.items() if 'technology' in v) (n.b. use d.iteritems() in Python2).

Runnable demo:

d = {
    4722: "['children', 'dance', 'education','technology', 'teaching']",
    3200: "['alternative energy', 'sustainability', 'technology']",
    1636: "['computers', 'performance', 'simplicity', 'software', 'ice']",
    1697: "['MacArthur grant', 'inequality', 'technology', 'pollution']"
}

result = sum(k for k,v in d.items() if 'technology' in v)
assert result == 9619

References:

Upvotes: 4

TitanFighter
TitanFighter

Reputation: 5074

your_data = {
    4722: "['children', 'dance', 'education','technology', 'teaching']",
    3200: "['alternative energy', 'sustainability', 'technology']",
    1636: "['computers', 'performance', 'simplicity', 'software', 'ice']",
    1697: "['MacArthur grant', 'inequality', 'technology', 'pollution']"
}

sum_up = 0
for k, v in your_data.items():
    if 'technology' in v:
        sum_up += k

print('sum_up:', sum_up)

Upvotes: 1

Related Questions