'i want to add the even values of the key in dictionary to the other dictionary
#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.
Solution 1:[1]
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
.
Solution 2:[2]
Solution 1 (Using Dictionary Comprehension)
See @j1-lee's answer
dict1 = {"1":"one", "2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","10":"10"}
dict2 = {k: v for k, v in dict1.items() if int(k) % 2 == 0}
print(dict2)
Output
{'2': 'two', '4': 'four', '6': 'six', '8': 'eight', '10': '10'}
Do keep in mind that you should avoid using dict
as a variable name as @j1-lee correctly pointed out:
Note that using dict as a custom variable name is strongly discouraged, as it overwrites the built-in function dict.
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.
Solution 2 (Using filter()
and lambda
expressions)
You can combine the use of the filter()
function with lambda
expressions to solve your problem in a single line (Inspired from @THUNDER 07's answer).
- Convert the
dict1
items to a list that contains both the key and value pair:list(dict1.items()
- Use a
lambda
expression for everykey
,value
pair that:- converts the
key
to anint
int(x[0])
- and then checks if the first element
x[0]
in the pair is even or not(int(x[0])%2 == 0)
- converts the
filter()
will then add thatkey
,value
pair to the resulting dictionary- We then convert the result to a dictionary by calling
dict()
hence why it's better to usedict1
instead ofdict
for a dictionary variable name
dict1={"1":"one", "2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","10":"10"}
dict2 = dict(filter(lambda x: (int(x[0])%2 == 0), list(dict1.items())))
print(dict2)
Output
{'2': 'two', '4': 'four', '6': 'six', '8': 'eight', '10': '10'}
Why use lambda expressions?
We use lambda functions when we require a nameless function for a short period of time.
Solution 3 (Simple for
loop)
A simple intuitive way to understand more what's going on would be to loop over each key in the first dictionary.
- Loop over each key in the source dictionary
- Convert the key to an integer:
int(key)
- Check if that key is even using modulo
if(int(key) % 2 == 0)
One common thing to do with conditionals is to check if a number is odd or even. If a number is evenly divisible by 2 with no remainder, then it is even. You can calculate the remainder with the modulo operator
- If the key is even, add the key, value pair from the first dictionary to the second dictionary
dict2[key] = dict[key]
Full code below:
dict1={"1":"one", "2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","10":"10"}
dict2={}
for key in dict1.keys():
if int(key) % 2 == 0:
dict2[key] = dict1[key]
print(dict2)
Output
{'2': 'two', '4': 'four', '6': 'six', '8': 'eight', '10': '10'}
Summary
I would recommend using Solution 1 and 2 as they are more advanced, however if you want to better understand what's going on Solution 3 might be more appropriate.
You can generalize this type of problem in a simple way by looping over the keys of the first dictionary and checking if a condition is true for each key as follows:
for key in dict1.keys():
if(condition):
dict2[key] = dict1[key]
print(dict2)
So this may be a duplicate How to filter a dictionary according to an arbitrary condition function?
Ultimately it's up to you whether you use dictionary comprehension, lambda expressions or for
loops, but depending on your application some solutions might be more suitable than others.
See:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | j1-lee |
Solution 2 |