Home > Mobile >  How to cast the key to int type in dictionary comprehension in Python?
How to cast the key to int type in dictionary comprehension in Python?

Time:07-07

Suppose I have two dictionaries

dict_a_to_c = {'803': 2, '808': 8, '30': 9, '37': 11, '38': 12, '39': 13, '481': 18, '816': 21, .....}
# length of dict_a_to_c is huge.
 
dict_a_to_b = {480:2, 37:5, 40: 9, 816:20, 148: 18}

And I am mapping them through keys using:

# converting key of dict_a_to_c to int
dict_a_to_c = {int(key):value for key, value in dict_a_to_c.items()}

dict_c_to_b = {dict_a_to_c[k]: dict_a_to_b[int(k)] for k in dict_a_to_b if k in dict_a_to_c}

Output of dict_c_to_b —> {11: 5, 21: 20}

But suppose if we want to cast the key to int type in the one line/logic of dict_c_to_b how can we do it in Python efficiently?

CodePudding user response:

You can cast to str instead of to int:

dict_c_to_b = {dict_a_to_c[str(k)]: dict_a_to_b[k] 
    for k in dict_a_to_b if str(k) in dict_a_to_c}

CodePudding user response:

If I undertand correctly:

dict_c_to_b = {k:dict_a_to_b[i] for v,k in dict_a_to_c.items()
               if (i:=int(v)) in dict_a_to_b}

output: {11: 5, 21: 20}

CodePudding user response:

I think you should change your last line to:

dict_c_to_b = {dict_a_to_c[str(k)]: dict_a_to_b[k] for k in dict_a_to_b if str(k) in dict_a_to_c}

And then there is no need to write the converting part!

  • Related