Home > Blockchain >  Converting/Merging a dictionary based on 2nd dictionary
Converting/Merging a dictionary based on 2nd dictionary

Time:06-13

I am on Python 3.9

What I have is two dictionaries.

dict1= {'ZS': [1, 2], 'ZP': [3], 'XS': [4, 5], 'XP': [6, 7]}
dict2= {'a': {}, 'b' : {}}

how do I take every two keys of dict1 and add them as dict-value in dict2.

Like below

required dict

result_dict= {'a': {'ZS': [1, 2], 'ZP': [3]}, 'b' : {'XS': [4, 5], 'XP': [6, 7]}}

CodePudding user response:

The problem of your question is that you didn't explain clearly what is the criteria of the splitting.

Another problem is that when you iniciate a dictionary inside a dictionary, like you did in dict2. if you send 'a' or 'b' values to a variable for example c:

c = dict2['a']

It won't create a new { }, it will pass the reference of the '{ }' inside dict2['a'] or dict2['b'] and when you change c it will change both c and dict2['a'] value

That is quite hacky, got stuck while trying to make a solution hehehe.

If the criteria you are using is the first letter of the key, you can do:

dict1 = {'ZS': [1, 2], 'ZP': [3], 'XS': [4, 5], 'XP': [6, 7]}
dict2 = {'a': {}, 'b': {}}
result_dict = {}
for x in dict2.keys():
    result_dict[x] = {}

for key in dict1.keys():
    if key[0:1] == "Z":
        result_dict['a'][key] = dict1[key]
    elif key[0:1] == "X":
        result_dict['b'][key] = dict1[key]

print(dict1)
print(dict2)
print(result_dict)

{'ZS': [1, 2], 'ZP': [3], 'XS': [4, 5], 'XP': [6, 7]}
{'a': {}, 'b': {}}
{'a': {'ZS': [1, 2], 'ZP': [3]}, 'b': {'XS': [4, 5], 'XP': [6, 7]}}

CodePudding user response:

You could do something like:

keys1 = list(dict1)
keys2 = list(dict2)
result_dict = {
    keys2[i]: {
        keys1[2*i]:dict1[keys1[2*i]], 
        keys1[2*i 1]:dict1[keys1[2*i 1]]
    } 
    for i in range(len(keys2))
}

But in my opinion it is a really bad habit to trust dictionary key's order (unless you use OrderedDict)

  • Related