CodeDependency
CodeDependency

Reputation: 135

Python: iterating over SOME key:value pairs in a dictionary, but not the whole dictionary

I have a series of dictionaries that basically all have the same keys, but different values assigned per dictionary.

For simplicity lets say I have 3 dictionaries:

dict_one = {
    "three letter code": "Arg:",
    "C": 1,
    "H": 2,
    "N": 3,
    "O": 4,
    "a_string": "nope",
}


dict_two = {
    "three letter code": "Doh:",
    "C": 5,
    "H": 6,
    "N": 7,
    "O": 8,
    "a_string": "nah",
}

dict_three = {
    "three letter code": "Uhg:",
    "C": 9,
    "H": 10,
    "N": 11,
    "O": 12,
    "a_string": "no",
}

Say I'd like to loop through each of these dictionaries and multiply the values contained in the keys "C" and "N" and "O" by 4. Because they are ints. We do math with ints.

I do not want to multiply "three letter code" or "a_string" Because they are strings, and whats the point of multiplying strings, right? (there is, just not for my case).

If you have a good way of tackling this then by all means, be my guest.

But I was thinking since all my dictionaries have key:value pairs that are in a consecutive order, I was wondering if it is possible to loop over them the same way you could loop over a chunk/range of indices in a list. For example:

arr = ["zero", "one", "two", "three", "four", "five"]

for i in range(2, 5):
    print(arr[i])

doesn't loop over and print the full list, Instead it only produces an output of :

two
three
four

Would a similar method of looping be possible for a dictionary? if not, that is alright, and I appreciate the time taken to help out a biology student who doesn't know a whole lot about coding.

Upvotes: 2

Views: 94

Answers (5)

MarianD
MarianD

Reputation: 14131

(Your question is a typical illustration of The XY Problem:-))

You may use the type() function to multiply only integer values:

import pprint                        # Only for nice test print

dict_one = {
    "three letter code": "Arg:",
    "C": 1,
    "H": 2,
    "N": 3,
    "O": 4,
    "a_string": "nope",
}

for key in dict_one:
    if type(dict_one[key]) is int:
        dict_one[key] *= 4

pprint.pprint(dict_one)

The output:

{'C': 4,
 'H': 8,
 'N': 12,
 'O': 16,
 'a_string': 'nope',
 'three letter code': 'Arg:'}

Upvotes: 2

CristiFati
CristiFati

Reputation: 41116

One way of achieving your goal (although it doesn't take into account the key order as you specified in the question) is using a dictionary comprehension (doesn't modify the original dictionary, but returns a new one instead). Here's an example for dict_one:

>>> dict_one = {
...     "three letter code": "Arg:",
...     "C": 1,
...     "H": 2,
...     "N": 3,
...     "O": 4,
...     "a_string": "nope",
... }
>>>
>>> dict_one_processed = {k: v * 4 if isinstance(v, (int,)) else v for k, v in dict_one.items()}
>>>
>>> dict_one_processed
{'three letter code': 'Arg:', 'C': 4, 'H': 8, 'N': 12, 'O': 16, 'a_string': 'nope'}

Upvotes: 1

AKX
AKX

Reputation: 168957

Dictionaries aren't in any real specific order (well, keys are in the order declared in Python 3.7+, but that's not the way to go here).

If you know which keys are integers beforehand, you can just loop over those keys, gather the values and do whatever:

int_keys = ["C", "H", "N", "O"]

for d in (dict_one, dict_two, dict_three):
    int_values = [d[key] for key in int_keys]
    print(int_values)  # You can do whatever you like with these

If you don't know which of the keys are integers, you can interrogate the values' types:


for d in (dict_one, dict_two, dict_three):
    int_values = [value for value in d.values() if isinstance(value, int)]
    print(int_values)  # You can do whatever you like with these

Both of these output

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]

Upvotes: 1

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

Try this:

required_keys = list('CHNO')
for dct in (dict_one,dict_two,dict_three):
    for keys in required_keys:
        dct[keys] *= 4

Upvotes: 2

ArunJose
ArunJose

Reputation: 2159

Here is a code to do this in one of your dicts

for i,j in dict_three.items():    
    if(type(j) is int):
        dict_three[i]=dict_three[i]*4

Upvotes: 1

Related Questions