Python create multiple dictionaries from values ​read from a list - python

I have the following list of values: Numbers = [1,2,3,4].
Is it possible to create a dictionary with the same name as the values ​​contained in the list?
Example: dictionary_1 = {}
dictionary_2 = {}
....
dictionary_Number.. {}
I would like to create these dictionaries automatically, without creating them manually, reading the numbers contained in the list

You may use the keyword exec in python. Here is an example of your solution,
List = [1, 2,3]
for ele in List:
dic = f"Dictionary_{ele}"
exec(dic+" = {}")
print(Dictionary_1, Dictionary_2, Dictionary_3, sep='\n')
you may use it according to you, but the disadvantage for it is that you will need to use exec every time you need to use it or you must know what would be the name outcome of the first use of exec ...
I hope I helped...

Use the inbuild functions and remember that a dictionary needs a tuble (key & value):
Python Dictionaries
Python Dictionary fromkeys() Method
Example-Code:
Numbers = [1,2,3,4]
Numbers_dict = dict.fromkeys(Numbers,"dict_value")
print(Numbers_dict)
This will output:
{'1': 'dict_value', '2': 'dict_value', '3': 'dict_value', '4': 'dict_value'}
If you want to get a single dictonaries for each list-value, you first have to create for each list-value an empty variable.
After this you have to fill this empty vairables within a loop.

Related

How to reset value of multiple dictionaries elegantly in python

I am working on a code which pulls data from database and based on the different type of tables , store the data in dictionary for further usage.
This code handles around 20-30 different table so there are 20-30 dictionaries and few lists which I have defined as class variables for further usage in code.
for example.
class ImplVars(object):
#dictionary capturing data from Asset-Feed table
general_feed_dict = {}
ports_feed_dict = {}
vulns_feed_dict = {}
app_list = []
...
I want to clear these dictionaries before I add data in it.
Easiest or common way is to use clear() function but this code is repeatable as I will have to write for each dict.
Another option I am exploring is with using dir() function but its returning variable names as string.
Is there any elegant method which will allow me to fetch all these class variables and clear them ?
You can use introspection as you suggest:
for d in filter(dict.__instancecheck__, ImplVars.__dict__.values()):
d.clear()
Or less cryptic, covering lists and dicts:
for obj in ImplVars.__dict__.values():
if isinstance(obj, (list, dict)):
obj.clear()
But I would recommend you choose a bit of a different data structure so you can be more explicit:
class ImplVars(object):
data_dicts = {
"general_feed_dict": {},
"ports_feed_dict": {},
"vulns_feed_dict": {},
}
Now you can explicitly loop over ImplVars.data_dicts.values and still have other class variables that you may not want to clear.
code:
a_dict = {1:2}
b_dict = {2:4}
c_list = [3,6]
vars_copy = vars().copy()
for variable, value in vars_copy.items():
if variable.endswith("_dict"):
vars()[variable] = {}
elif variable.endswith("_list"):
vars()[variable] = []
print(a_dict)
print(b_dict)
print(c_list)
result:
{}
{}
[]
Maybe one of the easier kinds of implementation would be to create a list of dictionaries and lists you want to clear and later make the loop clear them all.
d = [general_feed_dict, ports_feed_dict, vulns_feed_dict, app_list]
for element in d:
element.clear()
You could also use list comprehension for that.

name variables or append dictionaries

I am trying to either
create dictionaries names based on loop index e.g. mydict_1, mydict_2 etc.
or
append dictionaries in one dictionary
Through a loop I am getting sets of data and I want to be able to access them all at once or one by one.
for components in fiSentence.findall("components"):
operation = components.find('operation').text
target = components.find('target').text
targetState = components.find('targetState').text
...
all this going in a dictionary:
tempDict = {"operation":operation, "target":target, "targetState":targetState, ...}
and then outside of the loop I tried to store all of them in another dictionary but I only managed to do so with a list:
data.append(tempDict)
What I want is either to store them in different dictionaries as:
procedural_Step_1 = {"operation":operation, "target":target, "targetState":targetState}
procedural_Step_2 = {"operation":operation, "target":target, "targetState":targetState}
...
or
store them all in one dictionary of dictionaries:
data = {"procedural_Step_1":{"operation":operation, "target":target, "targetState":targetState}, {"procedural_Step_2":{"operation":operation, "target":target, "targetState":targetState},...}
You can declare dict data before the loop and in the end of loop:
data['procedural_step_'+str(index)] = temp_dict
Index you can get with enumerate

Create many empty dictionary in Python

I'm trying to create many dictionaries in a for loop in Python 2.7. I have a list as follows:
sections = ['main', 'errdict', 'excdict']
I want to access these variables, and create new dictionaries with the variable names. I could only access the list sections and store an empty dictionary in the list but not in the respective variables.
for i in enumerate(sections):
sections[i] = dict()
The point of this question is. I'm going to obtain the list sections from a .ini file, and that variable will vary. And I can create an array of dictionaries, but that doesn't work well will the further function requirements. Hence, my doubt.
Robin Spiess answered your question beautifully.
I just want to add the one-liner way:
section_dict = {sec : {} for sec in sections}
For maintaining the order of insertion, you'll need an OrderedDict:
from collections import OrderedDict
section_dict = OrderedDict((sec, {}) for sec in sections)
To clear dictionaries
If the variables in your list are already dictionaries use:
for var in sections:
var.clear()
Note that here var = {} does not work, see Difference between dict.clear() and assigning {} in Python.
To create new dictionaries
As long as you only have a handful of dicts, the best way is probably the easiest one:
main = {} #same meaning as main = dict() but slightly faster
errdict = {}
excdict = {}
sections = [main,errdict,excdict]
The variables need to be declared first before you can put them in a list.
For more dicts I support #dslack's answer in the comments (all credit to him):
sections = [dict() for _ in range(numberOfDictsYouWant)]
If you want to be able to access the dictionaries by name, the easiest way is to make a dictionary of dictionaries:
sectionsdict = {}
for var in sections:
sectionsdict[var] = {}
You might also be interested in: Using a string variable as a variable name

Pythonic way to get the index of element from a list of dicts depending on multiple keys

I am very new to python, and I have the following problem. I came up with the following solution. I am wondering whether it is "pythonic" or not. If not, what would be the best solution ?
The problem is :
I have a list of dict
each dict has at least three items
I want to find the position in the list of the dict with specific three values
This is my python example
import collections
import random
# lets build the list, for the example
dicts = []
dicts.append({'idName':'NA','idGroup':'GA','idFamily':'FA'})
dicts.append({'idName':'NA','idGroup':'GA','idFamily':'FB'})
dicts.append({'idName':'NA','idGroup':'GB','idFamily':'FA'})
dicts.append({'idName':'NA','idGroup':'GB','idFamily':'FB'})
dicts.append({'idName':'NB','idGroup':'GA','idFamily':'FA'})
dicts.append({'idName':'NB','idGroup':'GA','idFamily':'FB'})
dicts.append({'idName':'NB','idGroup':'GB','idFamily':'FA'})
dicts.append({'idName':'NB','idGroup':'GB','idFamily':'FB'})
# let's shuffle it, again for example
random.shuffle(dicts)
# now I want to have for each combination the index
# I use a recursive defaultdict definition
# because it permits creating a dict of dict
# even if it is not initialized
def tree(): return collections.defaultdict(tree)
# initiate mapping
mapping = tree()
# fill the mapping
for i,d in enumerate(dicts):
idFamily = d['idFamily']
idGroup = d['idGroup']
idName = d['idName']
mapping[idName][idGroup][idFamily] = i
# I end up with the mapping providing me with the index within
# list of dicts
Looks reasonable to me, but perhaps a little too much. You could instead do:
mapping = {
(d['idName'], d['idGroup'], d['idFamily']) : i
for i, d in enumerate(dicts)
}
Then access it with mapping['NA', 'GA', 'FA'] instead of mapping['NA']['GA']['FA']. But it really depends how you're planning to use the mapping. If you need to be able to take mapping['NA'] and use it as a dictionary then what you have is fine.

Dict into Dict Python

I am new in Python, Currently I am working data dictionary.
I expect to create dict into dict like this:
dates = {201101:{perf:10, reli:20, qos:300}, 201102:{perf:40, reli:0, qos:30}}
I already have the keys, and I have to created default values for initialization. i.e:
{201101:{perf:0, reli:0}, 201102:{perf:0, reli:0}}
how to do initiation and update the specifict dict. ie dates[201101[perf]] = 10.
Thanks!
To begin with
dates = {201101{perf=10, reli=20, qos=300}, 201102{perf=40, reli=0, qos=30}}
is not a valid python dict. This is:
dates = {201101: {'perf':10, 'reli':20, 'qos':300}, 201102:{'perf':40, 'reli':0, 'qos':30}}
Once you have initiated the dict of dict as:
dates = {201101:{'perf':0, 'reli':0}, 201102:{'perf':0, 'reli':0}}
you update it by doing:
dates[201101]['perf'] = 10
Demo:
>>> dates = {201101:{'perf':0, 'reli':0}, 201102:{'perf':0, 'reli':0}}
>>> dates[201101]['perf'] = 10
>>> dates
{201101: {'reli': 0, 'perf': 10}, 201102: {'reli': 0, 'perf': 0}}
First, you need to separate keys from their values with a :. Secondly, your keys need to be strings or numbers. Example.
dates = { 201101: {'perf': 10, 'reli':20, 'qos': 300} }
Your first dict:
dates={201101:{'perf':0, 'reli':0}, 201102:{'perf':0, 'reli':0}}
One way to update key's value:
date[201101]={'perf': 10, 'reli':20, 'qos': 300}
Another Method that you would need in case of run-time values is setdefault(i,[]) or {} instead of []. This allows you to dynamically create nested dictionaries instead of "flat".
For example:
dict = {}
for i in range(0,10):
dict.setdefault(i,{})
# Only now you can use the nested dict of level 1
for j in range(0,10):
dict[i][j] = j
This is just an example, you can dynamically create dict of any deep and with heterogeneous elements as list or other dict.

Categories