Home > Enterprise >  i want to add the even values of the key in dictionary to the other dictionary
i want to add the even values of the key in dictionary to the other dictionary

Time:03-05

#add the even values to dict to dict2
dict={"1":"one", "2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","10":"10"}
dict2={}

i want to add only the even values from the key (eg. "2":"two") to dictionary and print it.

CodePudding user response:

You can use dict comprehension:

dct = {"1":"one", "2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","10":"10"}

output = {k: v for k, v in dct.items() if int(k) % 2 == 0}
print(output)
# {'2': 'two', '4': 'four', '6': 'six', '8': 'eight', '10': '10'}

Note that using dict as a custom variable name is strongly discouraged, as it overwrites the built-in function dict.

CodePudding user response:

iterate through all the keys and add them to the dict2 if its even

dict={"1":"one", "2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","10":"10"}
dict2={}
for val in list(map(int,dict.keys())):
    if val%2 == 0:
        dict2[val] = dict[val]

using filter

dict2 = dict(filter(lambda ele:int(ele[0])%2==0, dict.items()))

CodePudding user response:

There are several ways to do this.

Solution A

The simple, naive way would be to loop over each key in the first dictionary.

Then convert the key to an integer: int(key)

Check if that key is even (if the remainder of modulo 2 is equal to 0 if(int(key) % 2 == 0) )

If the key is even, add the key and value from the first dictionary to the second dictionary dict2[key] = dict[key]

The full code is below along with the printed result:

dict={"1":"one", "2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","10":"10"}
dict2={}

for key in dict.keys():
    if int(key) % 2 == 0:
        dict2[key] = dict[key]
        
print(dict2)
{'2': 'two', '4': 'four', '6': 'six', '8': 'eight', '10': '10'}

Solution B

Another way of achieving this is by using dictionary comprehension (see @BrokenBenchmark and @j1-lee's answers).

You might ask, why use dictionary comprehension?

Dictionary comprehension is a powerful concept and can be used to substitute for loops and lambda functions. However, not all for loop can be written as a dictionary comprehension but all dictionary comprehension can be written with a for loop.

For loops are used to repeat a certain operation or a block of instructions in a program for a given number of times. However, nested for loops (for loop inside another for loop) can get confusing and complex. Dictionary comprehensions are better in such situations and can simplify the readability and your understanding of the code.

Further Reading

Solution C

You can also use lambda expressions (see @THUNDER 07's answer).

Why use lambda expressions?

We use lambda functions when we require a nameless function for a short period of time.

Further Reading

General Solution

You can generalize this approach by looping over the keys of the first dictionary and checking if a condition is true for each key as follows:

for key in dict.keys():
   if(condition):
      dict2[key] = dict[key]

But ultimately it's up to you whether you use for loops, dictionary comprehension or lambda expressions.

  • Related