How can I automate making dictionaries using python? - 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)

Related

Difficulty understanding changes to dictionary

I was looking through old posts in order to find a method of changing values in a dictionary by iterating through the items.
dictionary = {
1: [
{
"id": "1234",
"cow": "parts/sizes/lakes"
},
{
"id": "5151",
"cow": "minors/parts"
}
]}
def fetchanswers():
for item in dictionary[1]:
yield(item["id"], item["cow"])
for a, b in fetchanswers():
k = {}
k["id"] = a
k["cow"] = b.replace("parts", a)
My understanding is that yield returns the two items from either object in the dictionary and the for loop creates a new dictionary and appends the values obtained from fetchanswers() and parts is replaced by id.
I don't understand how k["id"] can be referred to when the dictionary is empty.
a method of changing values in a dictionary
Your values are strings. Strings are immutable, so you need to overwrite the dictionary using existing keys
You don't need another dictionary for this
# replace "parts" text value with the value of the id key
for item in list_of_dicts:
item["cow"] = item["cow"].replace("parts", str(item["id"]))
how k["id"] can be referred to
It's not a referral when there's an equal sign afterwards. It's an assignment

How to extract the given keys in one dictionary from another into a new dictionary (Python)

I'm trying to practice sets and dictionaries, and one thing I've been finding is myself stuck on this practice problem over and over.
For example if I have a dictionary like
employees =[
{
"name": "Jamie Mitchell",
"job": "Head Chef",
"city": "Toronto",
},
{
"name": "Michell Anderson",
"job": "Line Cook",
"city": "Mississauga",
}
]
How would I extract the second part of the dictionary from the first in order to only have the information on the right be in a new dictionary?
Quick Answer:
employees is a list of dictionaries so you can just directly index the list to get Michell:
newDict = employees[1]
More Detailed Answer:
Firstly, here is how you create a key-value pair in a dictionary:
dct = {}
dct['color'] = 'blue' # dct = {'color':'blue'}
Knowing this, all you would need to copy a dictionary is the keys and values. You can use the .keys(),.values(), and .items() methods of dictionaries to do this.
dct.keys() # returns a list of all the keys -> ['color']
dct.values() # returns a list of all the values -> ['blue']
dct.items() # return a list of all the pairs as tuples -> [('color','blue')]
There are other options to copy as another user has mentioned however I strongly suggest you get used to work with the 3 methods listed above. If you haven't already, make sure you are really comfortable with lists before you jump into dictionaries and combined structures. You already seem to know how to work loops so hopefully this is helpful enough, good luck!
You have them backwards; the outer one [] is a list. The inner ones {} are dictionaries.
You can get the second one with employees[1] (indexing starts from 0) or the last one with employees[-1] (in this case they are the same).
If you need a copy, you can call .copy() on the result:
second_employee = employees[1]
copied_details = second_employee.copy()

Creating nested dictionary dynamically in 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': {}}}}}}

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