Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
The community reviewed whether to reopen this question 10 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have odict_items that is looking like below. Here is the printed output of Ordereddict items that I have
odict_items([('S.No', '1'), ('Name', 'Ventura'), ('Location', 'Ph'), ('OL', 'ML'), ('Tech', 'IT'), ('Value', 223)])
odict_items([('S.No', '4'), ('Name', 'Ventura'), ('Location', 'Ph'), ('OL', 'ML'), ('Tech', 'IT'), ('Value', 223)])
odict_items([('S.No', '15'), ('Name', 'Ventura'), ('Location', 'Ph'), ('OL', 'ML'), ('Tech', 'IT'), ('Value', 223)])
How can I access the S.No key from each item and group the values 1, 4, 15?
I have to assume here that you have something similar to the following situation at some point:
ods = [ OrderedDict(<your data>), OrderedDict(<your data>), OrderedDict(<your data>) ]
for d in ods:
print(d.items())
If you still have the dictionaries these came from, you can and should access the value using d['S.No'].
If for some reason you do not still have the OrderedDicts themselves, you can make a function to get the value:
def get_sno(od_items):
for item in od_items:
if item[0] == 'S.No':
return item[1]
return None
Used as such:
snos = []
for d in ods:
snos.append(get_sno(d.item()) # preferably snos.append(d['S.No']) instead
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 months ago.
Improve this question
I have a dictionary
foo = {"/" : {"bar":"returnme"} }
and a list
example = ["/","bar"]
how do I use the list to return the value in "bar" ? (i.e. identical output to
foo["/"]["bar"] )
For clarity the value of the example list changes, the example could also be:
foo = {"/" : {"bar": {"morefoo": {"returnme"}} }}
example = ["/","bar","morefoo"]
foo[example] --> "returnme"
For other functionality in the script I will need to be able to use the example list to add/remove things to the 'final' dictionary.
You have to iteratively retrieve elements from a dictionary.
def get(tree, keys):
current = tree
for key in keys:
current = current[key]
return current
and it works:
>>> get({"/": {"bar": "returnme"}}, ["/", "bar"])
'returnme'
>>> get({"/": {"bar": {"morefoo": "returnme"}}}, ["/", "bar", "morefoo"])
'returnme'
>>>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
views.py
def vendor(request,pk):
current_shop = get_current_shop(request)
instance =get_object_or_404(Vendor.objects.filter(pk=pk,shop=current_shop,is_deleted=False))
vendor = instance.pk
purchases = Purchase.objects.filter(vendor=instance,is_deleted=False,shop=current_shop)
vendor_return = VendorReturn.objects.filter(vendor__pk=pk,shop=current_shop).values('id','return_date','total','date_added')
transaction = Transaction.objects.filter(shop=current_shop,is_deleted=False,vendor=instance).values('transaction_category__name','time','amount','date_added','vendor')
product_schemes = ProductScheme.objects.filter(vendor=instance,is_deleted=False,from_purchase=False).values('date_added','total_amount')
price_drops = VendorProductPriceDrop.objects.filter(vendor=instance).values('date_added','drop_amount')
result_list = sorted(chain(transaction, purchases, product_schemes, price_drops, vendor_return),key=itemgetter('date_added'),reverse=True)
context = {
"instance" : instance,
"purchases": purchases,
"vendor_return": vendor_return,
'product_schemes': product_schemes,
"price_drops": price_drops,
"transaction": transaction,
'result_list': result_list,
"title" : "Vendor : " + instance.name,
"single_page" : True,
}
return render(request,'vendors/vendor.html',context)
purchases is a normal QuerySet that yields model instances when iterated over. All your other queries are values querysets, these yield dictionaries when iterated over.
itemgetter will only work on objects that support key lookups, like dictionaries, models do not support this. You need to change all your queries to be the same "type" and use itemgetter or attrgetter appropriately.
A quick fix is to turn purchases into a values queryset
purchases = Purchase.objects.filter(vendor=instance,is_deleted=False,shop=current_shop).values()
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a function that returns a list of dictionaries like this:
[{'Status': 'Deleted', 'Name': "My First Test"}, {'Status': 'Modified', 'Name': "My First Test"}]
As you can see, "My First Test" is in there twice. Normally this wouldn't be an issue, however, based on what I know about what's happening on the back-end, the only dict that I actually want is the "Modified" dict.
Essentially, I'm looking for a way to say "if dict['Status'] == 'Modified' and dict['Status'] == 'Deleted' for the same Name, delete the one with the 'Deleted' status."
I don't know if I understood well your question.
But it's a tip:
list = [
{
'Status': 'Deleted',
'Name': "My First Test"
},
{
'Status': 'Modified',
'Name': "My First Test"
}]
filterd_list = [l for l in list if l['Status'] == 'Modified']
print(filterd_list) # Only the modified one will be printed
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm creating a dictionary from the college scorecard API, but I'm having trouble joining integer queries to my dictionary (ie. "2015.student.size"). How would I do that in my code? I've tried "str() for f in", but that doesn't seem to work.
This is what I've written in Python so far:
import requests
import json
def main():
url = 'https://api.data.gov/ed/collegescorecard/v1/schools.json'
payload = {
'api_key': "api_key_here",
'_fields': ','.join([
'school.name',
'school.school_url',
'school.city',
'school.state',
'school.zip',
]),
'school.operating': '1',
'2015.academics.program_available.assoc_or_bachelors': 'true',
'2015.student.size__range': '1..',
'school.degrees_awarded.predominant__range': '1..3',
'school.degrees_awarded.highest__range': '2..4',
'id': '240444',
}
data = requests.get(url, params=payload).json()
for result in data['results']:
print(','.join(result.values()))
main()
What happens when I run the program:
vagrant#vagrant:/vagrant/scripts$ python test.py
Madison,www.wisc.edu,University of Wisconsin-Madison,WI,53706-1380
When I add "print data":
{u'results': [{u'school.city': u'Madison', u'school.school_url': u'ww
w.wisc.edu', u'school.name': u'University of Wisconsin-Madison', u'sc
hool.state': u'WI', u'school.zip': u'53706-1380'}], u'metadata': {u'p
er_page': 20, u'total': 1, u'page': 0}}
I think you are making this more difficult than necessary. Instead of the for loop, you can do
print(data)
Or if you want each dictionary from the list to be on its own line, instead of
print(','.join(result.values()))
Just do
print(result)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a dictionary like:
{'6400': {'6401': '1.0', '6407': '0.3333333333333333', '6536': '0.0', '6448': '0.0'}}
And I would like to product a structure similar to preferably in Pyspark:
('6400',['6400','6401','1.0'])
('6400',['6400','6407','0.3333333333333333'])
('6400',['6400','6536','0.0'])
('6400',['6400','6448','0.0'])
If you do this in python you can use following code to produce the structure you want.
d = {'6400': {'6401': '1.0', '6407': '0.3333333333333333', '6536':
'0.0', '6448': '0.0'}}
result = []
for outer_e in d:
for inner_e in d[outer_e]:
e = [outer_e, inner_e, d[outer_e][inner_e]]
e = (outer_e, e)
result.append(e)
Little bit bulky, but another way to solve problem:
In [1]: d = {'6400': {'6401': '1.0', '6407': '0.3333333333333333', '6536': '0.0'
...: , '6448': '0.0'}}
In [2]: map(lambda item: [(item[0], [item[0], *i]) for i in item[1].items()], d.items())
Out[2]: <map at 0x104563e48>
In [3]: list(_)
Out[3]:
[[('6400', ['6400', '6401', '1.0']),
('6400', ['6400', '6407', '0.3333333333333333']),
('6400', ['6400', '6536', '0.0']),
('6400', ['6400', '6448', '0.0'])]]
And since it unordered dict object, you can't rely on order.