I've seen something like this construction somewhere:
list.append({
'title': scName,
'link': scLink,
})
print('Names:', list['title'])
print('Links:', list['link'])
Can you please show a working example?
Here, the dict is being appended to a list. And to use inner data, we've to put list[<index_of_inner_dict>][key_of_that_data]. In short, we've to go to the whole inner data index, then the index of required value. Here we have only one dict, it is simply list[0]. Also, scName and scLink are not defined, I'm assuming that they are simple strings. Your code:
l=[]
l.append({
'title': "scName",
'link': "scLink"
})
print (l)
print('Names:', l[0]['title'])
print('Links:', l[0]['link'])
What I believe you are asking is for someone to give you an example of how to use a dictionary. To give some background on dictionaries, they store information in key-value pairs. The key, which is the "index name" you mentioned in your title is mapped to a value stored. You can read here if you are still confused.
For the code example you gave, what it looks like you are attempting to do is add multiple dictionaries to a list and then access those values. Here is an example.
lst_of_employees = []
lst_of_employees.append({"name": "John", "salary": "10000"})
lst_of_employees.append({"name": "Jane", "salary": "20000"})
for emp in lst_of_employees:
print(f"{emp['name']} makes ${emp['salary']} a year.")
You can make the value of the key-value pair whatever you would like. Here is an example with the value stored at the key "salary" as another dictionary.
lst_of_employees = []
lst_of_employees.append({"name": "John", "salary": {"base": 8000, "bonus": 2000}})
lst_of_employees.append({"name": "Jane", "salary": {"base": 15000, "bonus": 5000}})
for emp in lst_of_employees:
employee = emp["name"]
base = emp["salary"]["base"]
bonus = emp["salary"]["bonus"]
print(f"{emp['name']} makes ${base+bonus} a year.")
Related
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()
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)
I used python to get a json response from a website ,the json file is as follows:
{
"term":"albany",
"moresuggestions":490,
"autoSuggestInstance":null,
"suggestions":[
{
"group":"CITY_GROUP",
"entities":[
{
"geoId":"1000000000000000355",
"destinationId":"1508137",
"landmarkCityDestinationId":null,
"type":"CITY",
"caption":"<span class='highlighted'>Albany</span>, Albany County, United States of America",
"redirectPage":"DEFAULT_PAGE",
"latitude":42.650249,
"longitude":-73.753578,
"name":"Albany"
},
{},
{},
{},
{},
{}
]
},
{},
{},
{}
]
}
I used the following script to display the values according to a key:
import json
a =['']
data = json.loads(a)
print data["suggestions"]
This displays everything under 'suggestions' from the json file, however If I want to go one or two more level down,it throws an error.For Eg. I wanted to display the value of "caption", I searched for the solution but could not find what I need.I even tried calling :
print data["suggestions"]["entities"]
But the above syntax throws an error.What am I missing here?
data["suggestions"] is a list of dictionaries. You either need to provide an index (ie data["suggestions"][0]["entities"]) or use a loop:
for suggestion in data["suggestions"]:
print suggestion["entities"]
Keep in mind that "entities" is also a list, so the same will apply:
for suggestion in data["suggestions"]:
for entity in suggestion["entities"]:
print entity["caption"]
If you see data within suggestions, is an array, so you should read like below:
print data["suggestions"][0]["entities"]
print data["suggestions"][0]["entities"][0]["caption"]
"Suggestion" key holds a list of dicts.
You can access it like this though if the positions of dictionary remain intact.
data["suggestions"][0]["entities"][0]["caption"]
I have a list of dicts, each dict has a data key. Each data key contains a bunch of attributes about a person, none of those attributes are mandatory:
persons = [
{"Name": "John", "data": {"Age": 23, "Gender": "Male"}},
{"Name": "Jane", "data": {"Age": 22, "Gender": "Female"}},
{"Name": "Harry", "data": {"Age": 22}},
{"Name": "Hermione", "data": {"Gender": "Female"}},
]
What I'd like to do is extract a distinct list of the Age values. I've done it like this:
ages = set()
persondatas = [person['data'] for person in persons]
for persondata in persondatas:
if 'Age' in persondata:
ages.add(persondata['Age'])
ages
which returns:
{22, 23}
which is exactly what I want but I'm thinking there must be a better, neater, way than looping over a list that I obtained using a list comprehension. Can I do the required work inside a list comprehension perhaps? My first aborted attempt went like this:
[person['data']['Age'] for person in l]
which failed:
KeyError: 'Age'
There must be a better way but I've fiddled around and can't work it out. Can anyone help?
You could add a conditional into your list comprehension - knock out both operations with one loop.
>>> {person['data']['Age'] for person in persons if 'Age' in person['data']}
set([22, 23])
Notice how I use curly braces ({}), instead of square brackets ([]), to denote a set comprehension.
Try this:
ages = set([person["data"]["Age"] for person in persons if "Age" in person["data"]])
One solution is a list comprehension combined with filter.
set(filter(None, [p['data'].get('Age') for p in persons]))
I'm trying to create an contact book indexed by 'nickname' that allows the user to save a persons name, address and number. But I don't quite understand how to do it using dictionaries, if I had it my way I would just use a list.
e.g
myList = [["Tom","1 Fairylane", "911"],["Bob","2 Fairylane", "0800838383"]]
And then if I wanted to see a certain contact I would just use some more code to search for a pattern. But I just can't figure out how to do it with a dictionary
You can start with this:
my_dict = {"Tom": {"name": "Tom Jones", "address": "1 Fairylane", "phone": "911"},
"Bob": {"name": "Bob Marley", "address": "2 Fairylane", "phone": "0800838383"}
}
then you can simply access records using
my_dict["Tom"]["name"]
or
my_dict["Bob"]["phone"]
Keys in a dictionary a unique. So if you have a list of contacts with no name twice you can use code like this:
contacts = {}
contacts['Tom'] = ["1 Fairylane", 911]
contacts['Bob'] = ["2 Fairylane", 0800838383]
so adding data to a dictionary is based on the access operator [].
If you want to initialize a dictionary with ready data, use code like this:
contacts = {'Tom' : ["1 Fairylane", 911],
'Bob' : ["2 Fairylane", 0800838383]}
access to a certain contact works like this:
print(contacts['Tom'])
Note, if you've got a second, say "Tom", this wouldn't work. You'd have to add date of birth or lastname or whatever to make it unique
As mentioned by DomTomCat you could set the dictionary key to be the first name, and the data then contained in a list. One thing to note is that dictionaries are unsorted. So whilst they provide a very fast search (they are essentially a hash table) for a key it will require you to do a bit of work if you wish to display sorted subsets of results.