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'
>>>
Related
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 last month.
Improve this question
How do I print the value of animals from the list?
[{'Url': 'https://www.somewebsite.html',
'Fruits': [],
'Animals': ['Fox'],
'Cars': ['Toyota']},
Thats is an dictionary inside list, so
l = [{'Url': 'https://www.somewebsite.html',
'Fruits': [],
'Animals': ['Fox'],
'Cars': ['Toyota']},
print(l[0]) # return dictionary
print(l[0]['Animals']) # return the list '['Fox']', that can be accessed by index 0.
I don't see the point of a list in there so I think what you are looking for is a dictionary that looks like this:
d = {
'key': 'value',
...
}
This is the easiest way to have paired items and to have a keyword that will give you more information about something. For example it could be used as information about products in a store where you can get the price and category for example.
To access these values you simply use this line of code: d['key'] or d.get('key')
So for this example you want to organize your items inside a dictionary like this:
items = {
'Fruits': [],
'Animals': ['Fox'],
'Cars': ['Toyota']
}
print(items['Animals']) # This gives you the list that in this example looks like this: ['Fox']
animals = items['Animals'] # This stores the list from above in a variable
print(items['Animals'][0]) # Out: 'Fox'
print(items.get('Animals')[0]) # Out: 'Fox'
print(animals[0]) # Out: 'Fox'
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 12 months ago.
Improve this question
I have the code below.
import json
name = " "
username = " "
ip_address = " "
with open('data6.json', 'r') as myfile:
data = json.load(myfile)
for i in data:
print(i[0].get('Manufacturer'))
print(i[0].get('Name'))
print(i[0].get('IPAddress'))
The output is the code like that:
VMware, Inc.
DC01
None
None
None
['192.168.1.240,fe80::350e:d28d:14a5:5cbb']
None
DC01
None
But i want an output like:
VMware, Inc.
DC01
['192.168.1.240,fe80::350e:d28d:14a5:5cbb']
How can i organize my code according to output that i want?
data6.json is like in the below:
[[{"Manufacturer": "VMware, Inc.", "Model": "VMware7,1", "Name": "DC01"}], [{"Index": "1", "IPAddress": ["192.168.1.240,fe80::350e:d28d:14a5:5cbb"]}], [{"Name": "DC01", "UserName": null}]]
If you load your initial json File you have:
one list -> contains 3 one-element lists -> contains the dict
If you have more of these nestes Lists in files, I would recommend to flatten them
If you want your data you have to access the correct one-element list, first index, then get the element in the one-element list, then choose the right value from the dict. Additionally you should close your file handler to close all resources before further working.
with open('data6.json', 'r') as myfile:
data = json.load(myfile)
print(data[0][0]['Manufacturer'])
print(data[0][0]['Name'])
print(data[1][0]['IPAddress'])
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 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 8 years ago.
Improve this question
I have a string which is of the form dictionary for sure.
I need to parse it and store it as a dictionary in python.
What i have tried is this:
myObj={}
tmp=""
if ':' in line:
key,value = line.split(':')
key = key.strip('"')
value = value.lstrip(' ').rstrip(',')
if value == '{':
tmp += key + '.'
if value == '}':
tmp = ''
if(value!="{"):
myObj[tmp + key] = value
Reading Line by Line and parsing it. But I am facing problems with different kind of formats.
For E.G.
{
"id": 1,
"name": "Foo",
"price": 123,
"tags": [ "Bar", "Eek" ],
"stock": {
"warehouse": 300,
"retail": 20
}
}
No use of eval or any built in function or library like json. Can I use regex here?
How do I do this?
You have JSON data, use the json library to parse it:
import json
data = json.loads(yourstring)
Python comes with batteries included, don't reinvent the wheel.