python-3.xmergeddictionaries

Merge two keys of a single dictionary in python


For a dictionary "a", with the keys "x, y and z" containing integer values. What is the most efficient way to produce a joint list if I want to merge two keys in the dictionary (considering the size of the keys are identical and the values are of interger type)?

x+y and y+z ? .

Explanation:

Suppose you have to merge two keys and merge them into a new list or new dict without altering original dictionaries.

Example:

a = {"x" : {1,2,3,....,50}
     "y" : {1,2,3,.....50}
     "z" : {1,2,3,.....50}
    }

Desired list:

x+y = [2,4,6,8.....,100]
y+z = [2,4,6,......,100]

Solution

  • A very efficient way is to do convert the dictionary to a pandas dataframe and allow it to do the job for you with its vectorized methods:

    import pandas as pd
    
    a = {"x" : range(1,51), "y" : range(1,51), "z" : range(1,51)}
    
    df = pd.DataFrame(a)
    x_plus_y = (df['x'] + df['y']).to_list()
    y_plus_z = (df['y'] + df['z']).to_list()
    
    print(x_plus_y)
    #[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]