Creating nested dictionary dynamically in python - python

I am trying to create a nested dictionary dynamically using python.
for example I need to create a function that will take the nodes and construct a nested dictionary with these nodes.
For example:
inputs:
'customers.applicant.individual.first_name'
output:
customers : {
applicant: {
individual:{
firstname: {}
}
}
}
and for each node, i need to make sure if it exist already if it does than skip else create the node. Can anyone please provide any help on this.
Thanks

You can take advantage of the fact that python dictionaries are mutable and do something like the following:
input_item1 = 'customers.applicant.individual.first_name.Bob'
input_item2 = 'customers.applicant.individual.first_name.Jim'
inputs = [input_item1, input_item2]
output_dictionary = dict()
for input_item in inputs:
current_dict = output_dictionary
for item in input_item.split('.'):
if item in current_dict:
current_dict = current_dict[item]
else:
current_dict[item] = dict()
current_dict = current_dict[item]
print(output_dictionary)
Basically, because dictionaries are mutable, if you modify 'current_dict', the entry in the larger dictionary that you are referencing gets updated too.
This gives an output of:
{'customers': {'applicant': {'individual': {'first_name': {'Bob': {}, 'Jim': {}}}}}}

Related

Python function that takes value from a dict and return full dictionary for the value

I'm trying to write a function that takes a value for a given key (User_ID) and return the full dictionary for that value. I understand that this can probably be achieved without writing a function but as a beginner I'm trying to build my knowledge with functions.
My data is a list of dictionaries and looks like this:
[
{
"User_ID":"Z000",
"DOB":"01.01.1960",
"State":"Oregon",
"Bought":["P1","P2"]
},
{
"User_ID":"A999",
"DOB":"01.01.1980",
"State":"Texas",
"Bought":["P5","P9"]
}
]
I wrote the following function but I realized that this is would only work for a dictionary but I have a list of dictionaries. How can I make it to take the User_ID value and return the full dictionary including the User_ID, DOB, State and Bought.
def find_user(val):
for key, value in dict_1.items():
if val == key:
return value
return "user not found"
You want to iterate over the list and compare the UserID of a dictionary with an input UserID:
def find_user(val, lsts):
for d in lsts:
if val == d['User_ID']:
return d
return "user not found"
Then
print(find_user('Z000', lsts))
prints
{'User_ID': 'Z000',
'DOB': '01.01.1960',
'State': 'Oregon',
'Bought': ['P1', 'P2']}
and
print(find_user('000', lsts))
prints
user not found
If however, your data is like:
d = { "Data": [{"User_ID":"Z000"},{"User_ID":"A999"} ]}
Then you can pass the list inside the dictionary to the function like:
find_user('Z000', d['Data'])
which returns
{'User_ID': 'Z000'}
If you really want to write a function for this task, your design is on the right track, but needs to be modified to account for the fact that you have a list of dictionaries. Something like this might work:
def find_user(userid):
for user_dict in big_list_of_user_dictionaries:
if user_dict['User_ID'] == userid:
return user_dict
However, you might be better off creating a new dictionary, where each key is the userid, and each value is one of your user info dictionaries. You could use Python's dictionary comprehensions to make such a dictionary quickly:
user_dict = {d['User_ID'] : d for d in big_list_of_user_dictionaries}
Then you could find the user info dictionary for any user by looking up their id in the user_dict, like this:
print(user_dict['Z000'])
Hope this code works for you.
def find_user(val):
for dict_key in l:
if dict_key["User_ID"] == val:
return dict_key
else:
return "User Not Found"
print(find_user("Z000"))
here l is the list that stores all your dictionaries.

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.

How can I automate making dictionaries using python?

I am doing a beginners Python course and the aim is to make a bunch of dictionaries.
Create three dictionaries: lloyd, alice, and tyler.
Give each dictionary the keys "name", "homework", "quizzes", and
"tests".
Have the "name" key be the name of the student (that is, lloyd's name
should be "Lloyd") and the other keys should be an empty list (We'll
fill in these lists soon!)
I did this by doing the following:
def make_dict(list_of_names):
for names in list_of_names:
names = {
"name": names,
"homework" : [],
"quizzes" : [],
"tests" : []
}
list_of_names = ["lloyd", 'alice', 'tyler']
make_dict(list_of_names)
Why does this not work? Should it work and is it just the Codeacademy development area that does not allow this to work? I realise I am being a little extra and that I could do this really straightforwardly and am purposely trying to be creative in how I do it.
In any case, what is the automated way to make a dictionary, based on lists of inputs?
You're creating a dictionary called names in each loop but not actually doing anything with it --
def make_dict(list_of_names):
results = []
for names in list_of_names:
names = {
"name": names,
"homework" : [],
"quizzes" : [],
"tests" : []
}
results.append(names)
return results
list_of_names = ["lloyd", 'alice', 'tyler']
my_dicts = make_dict(list_of_names)
This keeps track of the names dicts you have created, and then gives them to you at the end.
What is the automated way to make a dictionary, based on lists of
inputs?
You can use a dictionary comprehension here. A generator can avoid the need for boilerplate list construction code. In this solution, we yield items for each name in a list. Calling list then exhausts the generator, and we can assign the list to the variable my_dicts.
def make_dict(lst):
for name in lst:
d = {k: [] for k in ('homework', 'quizzes', 'tests')}
d['name'] = name
yield d
list_of_names = ['lloyd', 'alice', 'tyler']
my_dicts = list(make_dict(list_of_names))
You are creating three dictionaries; however, each one overwrites the previous one by assigning to the same variable names, and the last one is garbage collected because the only reference to it is a local variable that goes out of scope when make_dict returns.
You just need to return the created dict. For this exercise, it doesn't sound like you really need a loop.
def make_dict(name):
return {
"name": name,
"homework" : [],
"quizzes" : [],
"tests" : []
}
lloyd = make_dict("lloyd")
alice = make_dict("alice")
tyler = make_dict("tyler")
Vegetables={"tamato":40,"carrot":50,"onion":60,"green chillies":20,"red chillies":40,"capsicum":20,"radish":30,"drumstick":40,"beetroot":50,"peas":90}
Print(vegetables)

Using a python api that stores a dict in a list of dicts...with no key values

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")]
}

Appending something to a list within a dict within a list in Python

I am attempting to create a list of dicts which will have the following structure:
[
{
'id': '234nj233nkj2k4n52',
'embedded_list': []
},
{
'id': 'jb234bhj23423h4b4',
'embedded_list': []
},
...
]
Initially, this list will be empty.
What I need to be able to do is:
Check to see if a dict with a specific id exists in the list already
If a dict containing that id exists, append something to it's embedded_list
If a dict containing that id does not exist, create a dict, append it to the list.
I am aware of being able to test if a dict exists in a list based on something inside that dict using something like this:
extracted_dict = next((item for item in list if item['id'] == unique_id), None)
I am unsure of how to append something to a list within a dict within a list efficiently. Is there an obvious way which I'm not seeing (probably)?
Thank you in advance.
Your data structure should be a dictionary of dictionaries in the first place:
{'234nj233nkj2k4n52': {'embedded_list': []},
'jb234bhj23423h4b4': {'embedded_list': []},
... }
This will make all your desired operations much easier. If the inner dictionaries only contain the embedded list, this can be further simplified to
{'234nj233nkj2k4n52': [],
'jb234bhj23423h4b4': [],
... }
Now, all you need is a collections.defaultdict(list):
from collections import defaultdict
d = defaultdict(list)
d['234nj233nkj2k4n52'].append(whatever)
or just a simple dic
{
'234nj233nkj2k4n52' : [],
'jb234bhj23423h4b4' : []
}

Categories