I have a problem. I am new to django and trying to figure out how can I get specific values out of a list and a dict from views.py. I have the following dict output:
{'meta_title': u'Alaska State Fair Events', 'varos_id': 2886429L, 'longitude': -149.13053600000001, 'name': u'Palmer', 'thumbnail_id': 8406L, 'image': u'photologue/photos/2c18fe09-275b-4770-aab6-230cff72b2ee.jpg', 'orszag_id': u'US', 'helyszin': u'Alaska State Fair, 2075 Glenn Highway Palmer, AK 99645, United States ', 'slug': u'alaska-state-fair-palmer-ak', 'latitude': 61.580159999999999, 'allam_id': u'AK', 'nev': u'Alaska State Fair, Palmer, AK', 'id': 2886429L}
What I want to do is quite simple. I want to address the variables like image=szorakozohelyquery('image') which would result in
image=photologue/photos/2c18fe09-275b-4770-aab6-230cff72b2ee.jpg
Is there an easy way to do this? Also what is the easiest way to do this from a list?
d.get('image','default value') willprevent you from key error if key is not there in dictionary d
>>> d ={'image':'a.jpg'}
>>> d.get('image','not found')
'a.jpg'
>>> d={}
>>> d.get('image','not found')
'not found'
>>>
d['image'] will get you the value for key: 'image', from the dict: d.
... which will be: u'photologue/photos/2c18fe09-275b-4770-aab6-230cff72b2ee.jpg'.
"Also what is the easiest way to do this from a list?"
A list is a different data structure:
>>> my_list = ['a', 'b', 'c']
>>> print my_list[0]
a
see: http://docs.python.org/tutorial/datastructures.html for more info on lists and dicts.
Related
How do you use Python to accomplish the following:
I have the following list
StateCityList = [["Kansas","Overland Park"],
["Kansas","Lenexa"],
["Kansas","Olathe"],
["Missouri","Kansas City"],
["Missouri","Raytown"],
["Missouri","Independence"],
["Texas","Dallas"],
["Texas","Houston"],
["Texas","San Antonio"]]
I want to get all the cities in a certain state into a separate list like this
Kansas =[["Kansas","Overland Park],
["Kansas","Lenexa"],
["Kansas","Olathe"]]
Missouri = [["Missouri","Kansas City"]
["Missouri","Raytown"]
["Missouri","Independence"]]
Texas = [["Texas","Dallas"]
["Texas","Houston"]
["Texas","San Antonio"]]
Thanks
You can use operator.itemgetter and itertools.groupby:
>>> from itertools import groupby
>>> from operator import itemgetter
>>> {k: list(g) for k, g in groupby(StateCityList, key=itemgetter(0))}
{'Kansas': [['Kansas', 'Overland Park'],
['Kansas', 'Lenexa'],
['Kansas', 'Olathe']],
'Missouri': [['Missouri', 'Kansas City'],
['Missouri', 'Raytown'],
['Missouri', 'Independence']],
'Texas': [['Texas', 'Dallas'],
['Texas', 'Houston'],
['Texas', 'San Antonio']]}
NOTE:
If StateCityList is not sorted by state name, then use this:
{k: list(g) for k,g in groupby(sorted(StateCityList, key=itemgetter(0)), itemgetter(0))}
Using setdefault:
StateCityDict = {}
for state, city in StateCityList:
StateCityDict.setdefault(state, []).append([state, city])
Somewhat more beginner-friendly code. I like the one above though.
StateCityList = [["Kansas","Overland Park"],
["Kansas","Lenexa"],
["Kansas","Olathe"],
["Missouri","Kansas City"],
["Missouri","Raytown"],
["Missouri","Independence"],
["Texas","Dallas"],
["Texas","Houston"],
["Texas","San Antonio"]]
sc = {}
for state, city in StateCityList:
if state in sc:
sc[state].append((state,city))
else:
sc[state] = [(state, city)]
# print
for state in sc:
print(state, sc[state])
solution using set
You don't need to import any packages to perform this task as you can identify the list of unique States using set, :
# find unique set of states using "set"
states=set([k[0] for k in StateCityList])
# build dictionary splitting by city:
res={}
for s in states:
res[s]=[k for k in StateCityList if k[0]==s]
giving the resulting dictionary:
{'Missouri': [['Missouri', 'Kansas City'], ['Missouri', 'Raytown'], ['Missouri', 'Independence']], 'Texas': [['Texas', 'Dallas'], ['Texas', 'Houston'], ['Texas', 'San Antonio']], 'Kansas': [['Kansas', 'Overland Park'], ['Kansas', 'Lenexa'], ['Kansas', 'Olathe']]}
nicer output: Avoid duplication of State information in result
This answers the question as you set it, but do you really need to repeat the State within the resulting list? I think it is neater to leave it out in this way:
res={}
for s in set([k[0] for k in StateCityList]):
res[s]=[c for k,c in StateCityList if k==s]
Which gives a neater dictionary, with the key=State and the entry a list of the cities:
{'Missouri': ['Kansas City', 'Raytown', 'Independence'],
'Texas': ['Dallas', 'Houston', 'San Antonio'],
'Kansas': ['Overland Park', 'Lenexa', 'Olathe']}
alternative using zip
I haven't tested it but suspect it is faster for large datasets if you substitute the first iterator for the zip command, although I prefer the iterator in most circumstances as I find the code clearer and easier to understand:
res={}
for s in set(list(zip(*StateCityList))[0]):
res[s]=[k for k in StateCityList if k[0]==s]
This question already has answers here:
Return a default value if a dictionary key is not available
(15 answers)
Does Python have a defined or operator like Perl? [duplicate]
(2 answers)
Make value_counts() return 0 if the value does not occur
(1 answer)
Default dict keys to avoid KeyError
(4 answers)
Closed 5 years ago.
I have a situation where some city names need to be renamed, so I am using a dict where the keys are the old city names and the values are the new ones. However, only some cities need to be renamed so not all possible cities are in the dict.
The only way I know how to do it is to except a KeyError when the city doesn't need to be renamed, which works, but I'm not sure if this is bad practice, or if there are any downfalls to this. Is there something I am missing?
# Set Venue
venue_name = unidecode(cell[2].get_text())
try:
# Correct venue names i.e. Cairns, QLD = Cairns
venue_name = VENUE_NAMES_DICT[venue_name]
except KeyError:
pass
As #jarmod suggests, you can use the .get() method of the standard Dictionary to provide a default value in case the key is missing. What isn't described is that this approach enables you to turn your problem into a one-liner by passing the venue_name value to .get() as the default value.
# Set Venue
venue_name = unidecode(cell[2].get_text())
# Correct venue names i.e. Cairns, QLD = Cairns
venue_name = VENUE_NAMES_DICT.get(venue_name, venue_name)
If venue_name is present as a key in the dictionary, .get() will return the desired new value. If it isn't present, .get() will return the original value of venue_name unchanged. This eliminates the need for any conditional logic.
What you can do is use defaultdict
from collections import defaultdict
d=defaultdict(list) #this will return a empty list everytime a new key is used or if key exists it will appendt the value to the list
d[venue_name]=a
Example:
>>> from collections import defaultdict
>>> city_list = [('TX','Austin'), ('TX','Houston'), ('NY','Albany'), ('NY', 'Syracuse'), ('NY', 'Buffalo'), ('NY', 'Rochester'), ('TX', 'Dallas'), ('CA','Sacramento'), ('CA', 'Palo Alto'), ('GA', 'Atlanta')]
>>>
>>> cities_by_state = defaultdict(list)
>>> for state, city in city_list:
... cities_by_state[state].append(city)
...
for state, cities in cities_by_state.iteritems():
... print state, ', '.join(cities)
...
NY Albany, Syracuse, Buffalo, Rochester
CA Sacramento, Palo Alto
GA Atlanta
TX Austin, Houston, Dallas
You can use dict.get(key, default_value) and supply a default value.
You can use "in", like this:
data = ['Chicago', 'NYC', 'Boston', 'SD']
dictionary = {'NYC': 'New York', 'SD': 'San Diego'}
new_list = []
for x in data:
if x in dictionary:
new_list.append(dictionary[x])
else:
new_list.append(x)
print(new_list)
#output
['Chicago', 'New York', 'Boston', 'San Diego']
Using List comprehension
data = ['Chicago', 'NYC', 'Boston', 'SD']
dictionary = {'NYC': 'New York', 'SD': 'San Diego'}
new_list=[dictionary[x] if x in dictionary else x for x in data]
print(new_list)
['Chicago', 'New York', 'Boston', 'San Diego']
In general, throwing exceptions for non-exceptional situations is poor design. You want a defaultdict.
from collections import defaultdict
renames = defaultdict(lambda: None)
# Add the elements to renames here ...
Now, renames is a dictionary, except that if the key doesn't exist, it returns None rather than throwing, so you can just check if the value is None to see if it needs to be renamed.
I am attempting to select the distance from a googlemaps query. The data seems to have returned via a dictionary. However, I am not able to access the information I need.
What I am looking at
{'copyrights': 'Map data ©2017 Google', 'warnings': [], 'summary': 'NJ Tpke
S and I-95 S', 'legs': [{'traffic_speed_entry': [], 'distance': {'value':
365542, 'text': '227 mi'},
What I want returned "227 mi".
What I have tried is below
>>> dirs[0]['summary']
'NJ Tpke S and I-95 S'
>>> dirs[0]['summary'][0]['traffic_speed_entry'][0]
Traceback (most recent call last):
File "<pyshell#117>", line 1, in <module>
dirs[0]['summary'][0]['traffic_speed_entry'][0]
TypeError: string indices must be integers
I tried the approaches in these references, too:
accessing-elements-of-python-dictionary and
inverse-dictionary-lookup-in-python
I also imported into pandas, numpy, and tried to slice it.
Here's the code that creates the dictionary:
>>> import googlemaps
>>> from datetime import datetime
>>> gmaps = googlemaps.Client(key='APIKEY')
>>> start = '07042'
>>> end = '20024'
>>> dirs = gmaps.directions(start, end)
Does Google do something funny when they return a dictionary?
"traffic_speed_entry" is in the "legs" field, not the "summary". Let's take your attempt, one subscript at a time:
dirs[0]
I assume that this is the item you posted in the first code box.
dirs[0]['summary']
As you've noted already, this is the string 'NJ Tpke S and I-95 S'.
dirs[0]['summary'][0]
This is the letter 'N' at the start of that string.
dirs[0]['summary'][0]['traffic_speed_entry']
This is equivalent to
'N'['traffic_speed_entry']
You're trying to index one string with another.
SOLUTION
You need to access the field properly.
dirs[0]['legs'][0]['distance']['text']
I recommend that you try adding a single element at a time, checking that you got what you expected:
>>> dirs = [ {'copyrights': 'Map data 2017 Google', 'warnings': [],
'summary': 'NJ Tpke S and I-95 S',
'legs': [{'traffic_speed_entry': [],
'distance': {'value':365542,
'text': '227 mi'}}]},
"other dictionaries" ]
>>> dirs[0]
{'legs': [{'traffic_speed_entry': [],
'distance': {'text': '227 mi', 'value': 365542}}],
'summary': 'NJ Tpke S and I-95 S',
'copyrights': 'Map data 2017 Google', 'warnings': []}
>>> dirs[0]['summary']
'NJ Tpke S and I-95 S'
>>> dirs[0]['summary'][0]
'N'
>>> dirs[0]['legs']
[{'traffic_speed_entry': [],
'distance': {'text': '227 mi', 'value': 365542}}]
>>> dirs[0]['legs'][0]
{'traffic_speed_entry': [],
'distance': {'text': '227 mi', 'value': 365542}}
>>> dirs[0]['legs'][0]['distance']
{'text': '227 mi', 'value': 365542}
>>> dirs[0]['legs'][0]['distance']['text']
'227 mi'
dirs[0]['legs'][0]['distance']['text'] should work.
It means, that from the dict in dirs[0], select the element with key 'legs', which is a list.
Extract the zeroth element of that list and find the key 'distance' from that element (which is a dict).
In that last element find 'text', and return the corresponding string.
Note that: you were trying to access traffic_speed_entry which does not contain the information you wanted.
The miles you are looking for should be in
dirs[0]['legs'][0]['distance']['text']
Note that you have a list (in legs) within a dictionary that contains another dictionary!
EDIT, based on comment:
How do I read a list within a dictionary which contains another dictionary?
You just kinda pile on call onto the other one. See also the accepted answer above. Note that a list is indexed by position, e.g. legs[0] indicates the first item in legs (tutorial on lists). This item happens to be a dictionary in oyr case (it could have been anything, really). This dictionary, different from a list, can be accessed through its keys, as you did above (tutorial on dicts). Here, we want what's stored under the key distance. Alternatively, we could have pulled the key traffic_speed_entry out.
That is clearly what confused me. The distance, text is the list? Legs & dirs are the dictionary?
Note that lists are indicated by [ and ] in Python, dictionaries by { and }. Lists are lists of things (e.g. [1,'aaa']), while dictionaries associate keys with values (e.g. {key1:1, key2:'aaa'}). Try reading your example with that in mind.
You can assemble your example like so:
dirs is presumably a list; we use [0] to extract its first item.
This item is a dictionary (we know that because in the example you posted it is in {. we extract the value associated with the key legs by calling ['legs']. This value happens to be a list.
Just like above, we access the first item in that list through [0]. Etc.
I have pre-defined a dict of list of string triggers:
triggers = {'academic': ['studied at', 'studies at', 'studies', 'studies at'],
'age': ['years old','months old'],
'gender': ['male', 'female'],
'pets': ['dog','cat'],
'location': ['Lived in','Lives in']}
and I have a not previously known list of lists of grouped information data, example:
example_list_of_list = [['Former Teacher of math at'],
['Studies programming at', 'Stackoverflow'],
['Lives in','Chicago'],
['owns','dog', 'cat']
I want to append each matching list element to a new dictionary using the match pre-defined key value, such as:
{'academic': ['Former Teacher of math at'],
'age': None, # np.nan or []
'gender': None, # np.nan or []
'pets': ['owns','dog','cat']
'location': ['Lives in','Chicago']
}
Thanks!
You can do this using set semantics most easily, I think:
result = {}
for input in example_list_of_list:
for key, triggerset in triggers.items():
if not input.isdisjoint(triggerset):
result[key] = result.get(key,[]).append(input)
Though note a couple things:
triggers should be a dict of sets not lists.
example_list_of_lists should be a list of sets instead
result is a dict of lists of lists because more than one input might match
I have some data on a dictionary. Each key in the dictionary has several values, one of them is called 'state' which can be equal to Georgia, Washington, etc. I want to get the unique states. I tried doing this but I get an incorrect syntax error
s = set( value for key in r value = key['state'] )
How can I get all the states?
Edit:
The data structure I have is actually a list of dictionaries so I want to get the values of r[0]['state'], r[1]['state'], etc and make an unique list.
Based on your comment since you have a list of dictionaries you can use map function with passing dict.get method to it, to get all state values then you can loop over the values within a set :
s = set( value for value in map(lambda x:x.get('state'),r))
Or for get ride of lambda function you can use operator.itemgetter :
from operator import itemgetter
s = set( value for value in map(itemgetter('state'),r))
So you have a dictionary, and each key-value pair has another dictionary inside value, where one of the keys for these "inner" dictionary is state?
In that case:
my_dict = {'somekey': {'a':1,'b':2, 'state':'georgia'}, 'otherkey': {'a':1,'b':2, 'state':'washington'}}
[val['state'] for key, val in my_dict.iteritems()]
['georgia', 'washingon']
Just guessing at your data structure, but if it's like this:
r = {'home': {'address': '123 Oak Avenue', 'city': 'My town', 'state': 'State'},
'work': {'address': '456 Main Street', 'city': 'Big city', 'state': 'State'}}
then you can use this to retrieve the states:
s = set(r[key]['state'] for key in r)