This question already has answers here:
Access nested dictionary items via a list of keys?
(20 answers)
Use a dict to access nested instances of classes in Python
(3 answers)
How to convert string to class sub-attribute with Python
(3 answers)
Closed 4 years ago.
Consider the following dict:
{
"a" : {
"b" : [
entry,
entry,
...
]
}
}
Is there any way to address each entry given a key in the form "a.b"?
Ideally one could write something like dict[*("a.b".split("."))] and get dict["a"]["b"], but I have found no way to do it in Python yet.
Edit 2
Since no one seems to really care about quality code, I ended up using a plain old for loop:
data = { "a" : { "b" : "foo" } }
key = "a.b"
d = data
for k in key.split("."):
d = d[k]
d == data["a"]["b"] # True
Edit 3
Comments contain a valid solution:
import operator
from functools import reduce # forward compatibility for Python 3
data = { "a" : { "b" : "foo" } }
key = "a.b"
d = reduce(operator.getitem, key.split("."), data)
d == data["a"]["b"] # True
However, apart from this, I guess there is no way to exploit some language feature to do that, which kind of was the original question.
Related
This question already has answers here:
Edit the values in a list of dictionaries?
(4 answers)
Closed 1 year ago.
I have the following JSON, I want to be able to get the value for a certain key and update it accordingly.
So for example take a look at the key 'a' in the first JSON object, I want to be able to get its value '2' and then update the value for 'a' to whatever I want. It is important I can work with the value, incase I want to reformat date/time for example and update the key.
All help appreciated
x = "test" : [{
"a":"2",
"b":"12",
"c":"24",
"d":"223",
"e":"23",
},
{"a":"22",
"x":"24",
"c":"25",
"d":"21",
"e":"25",
},
{"a":"12",
"y":"23",
"c":"25",
"d":"23",
"e":"21",
}],
You could do this.
keyFor = 'a'
#get value
aVal = x['test'][0][keyFor]
#change value
aVal = int(aVal) + 2
#substitute in x
x['test'][0][keyFor] = aVal
print(x)
This question already has answers here:
How to use dict.get() with multidimensional dict?
(5 answers)
Closed 2 years ago.
I have to parse a JSON that is extremely variable.
Let's say that in its most complete form it's like this:
{
"a":{
"b":{
"c":4,
"d":[
"foo",
"bar"
]
},
"e":"fubar"
},
"f":"hello there"
}
However any one of those keys may be missing.
How can I convert the dict that json.loads will return in something that will return None if I try to access any missing key? I know that dict.get() has that behaviour but that only works in a single level dict.
You can provide a value in .get() that will return if the key is not found, it does not have to return None.
dict_.get('first_key', dict()).get('second_key')
This question already has answers here:
How to get a random value from dictionary?
(19 answers)
Closed 3 years ago.
I want to get a value "element":"value" from a dictionary in python.
import random
country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
}
random.choice(country)
It returns me the following :
File "C:\Users\${username}\AppData\Local\Programs\Python\Python37-32\lib\random.py", line 262, in choice
return seq[i]
KeyError: 10
My aim, is to select a random value and be left with 1 Country - City left in the dictionary.
This does not answer my question : How to get a random value from dictionary in python
You can use the items method to get the pairs, then transform it to a list that supports indexing:
random.choice(list(country.items()))
i think you can implement in following way
import random
country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
}
keys = list(country.keys())
random_key = keys[random.randint(0, len(keys)-1)]
print(country[random_key])
You can make a random.choice from the keys() of the dict for instance.
You could print the values or make a new dict with just that entry:
import random
country = {
"Spain":"Madrid",
"UK":"London",
"France":"Paris"
}
k = random.choice(list(country.keys()))
print(k, country[k])
print({k:country[k]})
First of all, there's no order in a dictionary. The only list can be used for random.sample.
So change your code to random.choice(list(country.items()))
This question already has answers here:
What is getattr() exactly and how do I use it?
(14 answers)
Closed 4 years ago.
following code to start:
products = [{
"id": x.id,
"fabric": x.fabric.name,
"fabricimg": x.fabric.fabric_cover.url,
} for x in entry_obj.all()]
cart_data = {
"products": products,
"total": cart_obj.total
}
return JsonResponse(cart_data)
This works fine for creating my list products with the dictionaries from the x(objects) in entry_obj.all().
But now I have the scenario that I have some x(objects) with no x.fabric.name, and instead will have to use a filler for example a simple string like "noname".
How can I use an if statement in the existing for loop to catch the case of name not existing and instead setting the key fabric to my string value?
I thought of using:
if hasattr(entry_obj,"name") > "fabric": x.fabric.name
else > "fabric": "noname"
But I'm unsure where to put it in the for loop plus how to iterate through the x(objects) in entry_obj for that matter so I can still give Json the right cart_data.
Use getattr with the 3rd default argument:
products = [{'id': x.id, 'fabric': getattr(x.fabric, 'name', 'noname'),
'fabricimg': x.fabric.fabric_cover.url} for x in entry_obj.all()]
This question already has answers here:
python: read json and loop dictionary
(2 answers)
Closed 6 years ago.
I have a piece of json which was converted to a dict using the json function.
From this:
{
"imageIds": [
{
"imageTag": "1.2",
"imageDigest": "sha256:8b67b1691b29e27a5ccbd6fea5c97c951a025ccd45b26d4c24567ca3c4c0f13b"
},
{
"imageTag": "1.0",
"imageDigest": "sha256:aa52a12bd6e516659452af5b9ed0fad8659f9e0cea6a986c6bfe02af388df189"
}
]
}
To this:
>>> print data
{u'imageIds': [{u'imageTag': u'1.2', u'imageDigest': u'sha256:8b67b1691b29e27a5ccbd6fea5c97c951a025ccd45b26d4c24567ca3c4c0f13b'}, {u'imageTag': u'1.0', u'imageDigest': u'sha256:aa52a12bd6e516659452af5b9ed0fad8659f9e0cea6a986c6bfe02af388df189'}]}
In this example the number of keys (imageIds) is fixed but there could be any amount of imageTags under imageIds.
What I'm trying to do is loop through the 'imageTag' elements to read the tag number and perform an operation. If i wanted to loop through the key it seems straightforward with something simple like:
for key in data:
print key, 'corresponds to', data[key]
However I'm uncertain on how I loop through the items under the key.
What I want to achieve is to print out:
1.2
1.0
Iterate over inner dict the same way you do for the outer one:
for key, value in data.iteritems():
#now value can be a dictionary as well
#for innerkey, innervalues in value[0].iteritems():
# print innerkey, innervalues
#in order to only print the elements that have imageTag as the key, simply do:
print value[0]['imageTag']