Home > Software design >  Creating a list of existing dictionaries in python
Creating a list of existing dictionaries in python

Time:02-12

I need to get a list of some dictionaries that I defined before.The dictionaries look like these: dic1={"D":1.4,"SD":1.4} dic2={"D":1.2,"SD":1.2,"L":1.6,"LR":1.6,"LR0.5":1.6,"LP":1.6,"LRF":0.5} dic3={"D":1.2,"SD":1.2,"L":1,"LR":1,"LR0.5":1,"LP":1,"LRF":1.6} And I expect a list like this:

list=[{"D":1.4,"SD":1.4},{"D":1.2,"SD":1.2,"L":1.6,"LR":1.6,"LR0.5":1.6,"LP":1.6,"LRF":0.5},                                                                               {"D":1.2,"SD":1.2,"L":1,"LR":1,"LR0.5":1,"LP":1,"LRF":1.6}]

How can I create it using a loop in python?

CodePudding user response:

list(filter(lambda a: type(a) == dict, locals().values()))

Will return all local variables with dict type as a list

CodePudding user response:

If you don't want to include all the dictionaries, do something like this:

lyst = []

# Define dic1
dic1 = {}
lyst  = [dic1]

# Code

dic2 = {}
lyst  = [dic2]

# etc...

Append the dictionaries to the list as you create them.

Of course, if you want to include all the dictionaries in the script, use @Daniil Ryzhkov's answer.

  • Related