I am making a console application that can load different dictionaries filled with Spanish words and definitions, my thinking here is that I want to make all the objects of my Dictionary class in this module and then import them via one dict_of_dicts into main.py. Instead of writing out each instantiating each individual object like so:
animals_dict = Dictionary('animals')
I wanted to loop through my dict_of_dicts and create them. Now when I do this I get a NameError because these objects are not yet defined, which makes sense I suppose, but I was wondering if there is a work around here to make these objects by a loop instead of just writing them out one by one.
# list of dictionaries loaded into main.py at runtime
from dict_class import Dictionary
dict_of_dicts = {'animals':animals_dict, 'nature':nature_dict, 'irregulars':irregulars_dict,
'clothes':clothes_dict, 'foodbev':foodbev_dict, 'phrases':phrases_dict,
'verbs':verbs_dict,'adjectives':adjectives_dict,'future':future_dict,'past':past_dict,
'wotd':wotd_dict}
for k,v in dict_of_dicts:
v = Dictionary(k) #k=self.name
print(v) #v=object
Suppose you have a list of names ['animals', 'nature', 'irregulars'] #etc
You can loop over that to create a new dictionary
my_dicts = {}
names = ['animals', 'nature', 'irregulars']
for name in names:
my_dicts[name] = Dictionary(name)
Or as a comprehension
my_dicts = {name: Dictionary(name) for name in names}
Besides the object not existing yet, the other problem you would run into is that when looping over a dictionary's items through dict.items, making an assignment on that name will not actually modify the dictionary.
for key, value in some_dict.items():
value = 'new' # Bad. Does not modify some_dict
for key in some_dict:
some_dict[key] = 'new' # Good. Does modify some_dict
names = ['animals', 'nature', 'foodbev'] # dict's names
dict_of_dicts = {}
for name in names:
dict_of_dicts[name] = Dictionary(k)
Related
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.
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
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
So i am using dictionary within a dictionary and every time I would try to extend the child_dict, which i do using a loop, only the last iteration value persists while the previous ones are over-written
parent_dict = defaultdict(list)
for getdata from datasource:
# I generate 'child_dict' here
parent_dict[parentDict_key] = child_dict
I tried to use .update(child_dict) method but it gives me
AttributeError: 'list' object has no attribute 'update'
I also tried to use .append() method but it makes the parent a list of dictionaries.
Is there any better way to add new child_dict to my parent_dict and just extend it during each iteration?
Well, if you want your values to be dictionaries and not lists you should use:
parent_dict = defaultdict(dict)
instead of:
parent_dict = defaultdict(list)
and then to generate:
parent_dict[parentDict_key][child_dict_key] = child_dict_value
The python API (gmusicapi) stores playlists as a list of dicts with the track info as a dict inside that dict.
-edit- this is wrong. it does have some sort of key when printed, but I cant find out how to access the keys within the dict.
list = [
{ ##this dict isn't a problem, I can loop through the list and access this.
'playlistId': '0xH6NMfw94',
'name': 'my playlist!',
{'trackId': '02985fhao','album': 'pooooop'}, #this dict is a problem because it has no key name. I need it for track info
'owner': 'Bob'
},
{ ##this dict isn't a problem, I can loop through the list and access this.
'playlistId': '2xHfwucnw77',
'name': 'Workout',
'track':{'trackId': '0uiwaf','album': 'ROOOCKKK'}, #this dict would probably work
'owner': 'Bob'
}
]
I have tried using for loops and accessing it through somethings like:
def playLists(self):
print 'attempting to retrieve playlist song info.'
playListTemp = api.get_all_user_playlist_contents()
for x in range(len(playListTemp)):
tempdictionary = dict(playListTemp[x])
The problem here is tempdictionary has a dict in it called tracks but I can't seem to access the keys/value pairs inside it no matter what I do.
when printed it returns something like:
[u'kind', u'name', u'deleted', u'creationTimestamp', u'lastModifiedTimestamp', u'recentTimestamp', u'shareToken', 'tracks', u'ownerProfilePhotoUrl', u'ownerName', u'accessControlled', u'type', u'id', u'description']
where 'tracks' is a dict containing artist, title, tracknumber etc
I also tried something like:
tempdictionary['tracks'][x]['title']
with no luck. Other times I have tried creating a new dict with tracks dict as a velue but then I get an error saying it needs a value of 2 and it found something like 11 etc.
im new to python so if anyone here could help with this I would be very thankful
it does have some sort of key when printed, but I cant find out how to access the keys within the dict.
Iterate over the dict:
for key in dct:
print(key)
# or do any number of other things with key
If you'll also be looking at the values of the dict, use .items() to save yourself a dict lookup:
for key, value in dct.items():
print(key)
print(value)
You might consider using classes to encapsulate common traits. Currently, each of your track and playlist dictionaries have a lot of duplicate code (ie. "track_id=", "owner="Bob"). Using classes reduces duplicate and makes your meaning more obvious and explicit.
class AudioTrack(object):
def __init__(self, ID, album=None):
self.id = ID
self.album = album
self.owner = 'Bob'
Create a single AudioTrack objects like this:
your_first_track = AudioTrack('02985fhao', 'pooooop')
Or create a list of AudioTrack objects like this:
your_tracks = [
AudioTrack("0x1", album="Rubber Soul"),
AudioTrack("0x2", album="Kind of Blue"),
...
]
In this way, you could inspect each AudioTrack object:
your_first_track.id #Returns '02985fhao'
Or do something for all AudioTrack objects in your_tracks:
#Prints the album of every track in the list of AudioTrack intances
for track in your_tracks:
print track.album
You might make playlists using dictionaries where:
my_playlist = {
id: "0x1",
name: "my playlist",
tracks: [AudioTrack("0x1", album="Rubber Soul"),
AudioTrack("0x2", album="Kind of Blue")]
}