Home > Mobile >  What are some pythonic ways to create a "chain-dict"?
What are some pythonic ways to create a "chain-dict"?

Time:06-01

Suppose:

dict_A = {'1': 'one', '2': 'two'}
dict_B = {'one': 'A', 'two': 'B'}
dict_C = {'1': 'A', '2': 'B'}

I want to create dict_C from dict_A and dict_B (Assume they have the same length). One could do this by

dict_C = {}
for k in dict_A: dict_C[k] = dict_B[dict_A[k]]

It works but I wonder if there are some pythonic or better ways (perhaps something like dict_C = dict_B[dict_A.values], of course it doesn't work).

CodePudding user response:

You can use dict comprehension and dict.items (although not sure whether it's significantly more pythonic; yours is good too!):

dict_A = {'1': 'one', '2': 'two'}
dict_B = {'one': 'A', 'two': 'B'}

dict_C = {k: dict_B[v] for k, v in dict_A.items()}
print(dict_C) # {'1': 'A', '2': 'B'}

CodePudding user response:

Subtle difference here whereby there is no reliance on the actual values/keys from either dictionary. What this does is take the values from dict_B and "pairs" them with keys from dict_A.

Is it more Pythonic? Is it better? Does it even make any sense at all? You decide.

dict_A = {'1': 'one', '2': 'two'}
dict_B = {'one': 'A', 'two': 'B'}
dict_C = {k:v for k, v in zip(dict_A.keys(), dict_B.values())}
print(dict_C)

Output:

{'1': 'A', '2': 'B'}
  • Related