Shubhangi Jain
Shubhangi Jain

Reputation: 13

How to combine variable number of dictionaries into one dictionary in Python?

I am trying to create a dictionary combining other dictionaries. But number of these dictionaries are variable. For fixed number of dictionaries I figured out the code:

x = {"Age": 20}
y = {"Age": 30}
z = {"Age": 40}
output = dict(rule1 = x,rule2 = y, rule3 = z)

In the above example new dictionary(output) is created using fixed number of dictionaries i.e. 3. Now I have 'n' number of dictionaries, how to combine these?

dict_1 = {"Age": 123}
dict_2 = {"Age": 45}
'
'
'
'
'
dict_n = {"Age": 56}
final_output = dict(dict_1, dict_2,......dict_n)

Upvotes: 0

Views: 1130

Answers (5)

Voz bonita
Voz bonita

Reputation: 380

As you receive the entries as age values, you can while loop through taking the age to a dict that just stands for ages and put them in other dict wich indexes every age

age = int(input())
#age dict
xyz = dict()

#future index
i = 0

output = dict()
while age != 0:
    xyz['Age'] = age
    #output index return a dict with key 'Age' and Age value
    output[i] = {'Age':xyz['Age']}
    i += 1
    age = int(input())

print(output)

With the entries 20 30 40 0 it outputs:

{0: {'Age': 20}, 1: {'Age': 30}, 2: {'Age': 40}}

Upvotes: 0

Paul Joseph
Paul Joseph

Reputation: 32

You can run a loop until the number of dictionaries in your program and use the update() method. EG-

def Merge(dictionaries):
    dictionary = {}
    for dict in dictionaries:
        dictionary.update(dict)
    return dictionary 
    
dict1 = {'a': 10, 'b': 8} 
dict2 = {'d': 6, 'c': 4} 
dictionaries = []
dictionaries.append(dict1)
dictionaries.append(dict2)
print(Merge(dictionaries))

Upvotes: 0

SCL
SCL

Reputation: 86

I would recommend you to use a list of dictionaries instead of scattered variables as they're very inappropriate for such operations.

This is how you can easily accomplish what you wanted with a given array (list) of dicts.

dictionary = {}

# Let's imagine the variable d as a list of dictionaries
d = [{"Example": "A"}, {"Example": "B"}, {"Example": "C"}]


for i, b in enumerate(d):
    dictionary[f"dict_{i}"] = b

print(dictionary)  # {'dict_0': {'Example': 'A'}, 'dict_1': {'Example': 'B'}, 'dict_2': {'Example': 'C'}}

Upvotes: 0

ThirtyOneTwentySeven
ThirtyOneTwentySeven

Reputation: 340

Instead of making n dictionaries and then trying to combine them into one, you could instead try to make a dictionary and then add each dictionary to it as you obtain the data.

For your situation:

class DictOfDict():
    def __init__(self):
        self.dict = {}
    def add_entry(self, rule_name, input_dict):
        self.dict[rule_name] = input_dict

    def get_entry(self, rule_name):
        try:
            return self.dict[rule_name]
        except KeyError:
            print("invalid rule name")
            return None

you can then use this as:

rule_dict = DictOfDict()
rule_dict.add_entry('rule_x', {"Age": 20})
rule_dict.add_entry('rule_y', {"Age": 30})
rule_dict.add_entry('rule_z', {"Age": 40})

you can access entries as

rule = rule_dict.get_entry('rule_z') # == {"Age:40"}

Upvotes: 0

hq7564
hq7564

Reputation: 11

There is no direct way that I know of. I would suggest using locals() to retrieve a dictionary of the locally available variables and their data. You can iterate over this and select which variables you would like to use (e.g. variables with only 1 letter in them)

Upvotes: 1

Related Questions