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']
Related
I'm having a JSON with nested values. I need to remove the key of the nested field and need to keep the values as plain JSON.
JSON(Structure of my JSON)
[
{
"id":"101",
"name":"User1",
"place":{
"city":"City1",
"district":"District1",
"state":"State1",
"country":"Country1"
},
"access":[{"status":"available"}]
}
]
I need to get the JSON output as:
Expected Output:
[
{
"id":"101",
"name":"User1",
"city":"City1",
"district":"District1",
"state":"State1",
"country":"Country1"
"access":[{"status":"available"}]
}
]
What i need is:
I need to parse the JSON
Get the Placefield out of the JSON
Remove the key and brackets and append the values to existing
Python
for i in range(0,len(json_data)):
place_data = json_data[i]['place']
print(type(place_data)) #dict
del place_data['place']
Any approach to get the expected output in python.?
One way to accomplish this could be by
for i in json_data:
i.update(i.pop("place"))
Another way to accomplish this with multiple "keys" updated...
This would only work for a single nested level as described in the original question
def expand(array):
flatten = list()
for obj in array:
temp = {}
for key, value in obj.items():
if isinstance(value, dict):
temp.update(value)
else:
temp.update({key:value})
flatten.append(temp)
return flatten
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 the best way to implement nested dictionaries?
(22 answers)
Closed 4 years ago.
sample input in place of separate_function:
separate_function = [('primary_1', 'val_1'), ('primary_1', 'val_2'), ('primary_3', 'val_2')]
Expected output i.e. my_dictionary:
{
"main": {
"primary_1": [
"val_1",
"val_2"
],
"primary_3": [
"val_2"
]
}
}
I want to create a dictionary, my_dictionary like above.
There are multiple keys like "main" in the expected output. To reduce the complexity of the problem, I have hard-coded it.
There is a generator function on which I need to iterate over to create this format. Again for simplicity, I have shown that as a list of tuples. I have tried so far:
from collections import defaultdict
my_dictionary = defaultdict(dict)
for primary_var, value in separate_function:
my_dictionary['main'][primary_var].append(value)
# This would have worked if I have expected values as string
# rather than a list in that case I can write the above line like this:
my_dictionary['main'][primary_var] = value
try, except can be used and if KeyError then assign first else append can be done, However, I am looking for a better clean solution. Please suggest. Thanks.
You can use dict.setdefault to initialize a new dict key with a new list:
my_dictionary = {'main': {}}
for k, v in separate_function:
my_dictionary['main'].setdefault(k, []).append(v)
my_dictionary would become:
{'main': {'primary_1': ['val_1', 'val_2'], 'primary_3': ['val_2']}}
This is one approach using collections.defaultdict.
Demo:
from collections import defaultdict
separate_function = [('primary_1', 'val_1'), ('primary_1', 'val_2'), ('primary_3', 'val_2')]
result = defaultdict(list)
for k, v in separate_function:
result[k].append(v)
my_dictionary = {"main": result}
print(my_dictionary)
Output:
{'main': defaultdict(<type 'list'>, {'primary_3': ['val_2'], 'primary_1': ['val_1', 'val_2']})}
This question already has answers here:
Checking a nested dictionary using a dot notation string "a.b.c.d.e", automatically create missing levels
(5 answers)
Closed 7 years ago.
I'm working on a Python script where I'm given lists of strings of the format: ['key1', 'key2', 'key2.key21.key211', 'key2.key22', 'key3'].
Each value in the list corresponds to an entry in a dictionary, and for entries structured like 'key2.key21.key211', they correspond to (in this example), a key 'key211' nested within 'key21', itself nested inside 'key2'.
The above list corresponds to the dictionary:
x = {
'key1' : 'value1',
'key2' : {
'key21' : {
'key211': 'value211'
},
'key22' : 'value22'
},
'key3' : 'value3'
}
The names are not necessarily as regular as key(n)+; they can be of the form food.vegetables.potato, for example. The only guarantees I have is that the key names themselves, in the dictionary, do not contain the . character, and that the dictionary definitely contains all the entries referenced in the original list.
My question is, given such a list of strings, how do I programmatically access the corresponding entries in a dictionary? I can think of a solution using eval(), as well as one using just a traversal/search, but I want to avoid calls to eval(), and I get the impression that a traversal with comparisons would be slow (since dicts aren't search trees), and would entail a lot of nasty exception handling.
One approach is to write a function to access keys in nested dicts.
def deep_access(x,keylist):
val = x
for key in keylist:
val = val[key]
return val
s = 'key2.key21.key211'
print deep_access(x,s.split('.'))
result:
value211
Another approach, if you want to use similar syntax as a normal dictionary access you could subclass dict and override __getitem__ to allow for nested access when a tuple of keys is provided:
class NestedDict(dict):
def __getitem__(self,keytuple):
# if key is not a tuple then access as normal
if not isinstance(keytuple, tuple):
return super(NestedDict,self).__getitem__(keytuple)
d = self
for key in keytuple:
d = d[key]
return d
>>> nd = NestedDict(x)
>>> nd['key2']
{'key22': 'value22', 'key21': {'key211': 'value211'}}
>>> nd['key2','key22']
'value22'
>>> nd['key2','key21']
{'key211': 'value211'}
>>> nd['key2','key21','key211']
'value211'
You can then similarly implement __setitem__ and __delitem__ as needed.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In Python how do I sort a list of dictionaries by values of the dictionary?
I'm writing a Python 3.2 app and I have a list of dictionaries containing the following:
teamlist = [{ "name":"Bears", "wins":10, "losses":3, "rating":75.00 },
{ "name":"Chargers", "wins":4, "losses":8, "rating":46.55 },
{ "name":"Dolphins", "wins":3, "losses":9, "rating":41.75 },
{ "name":"Patriots", "wins":9, "losses":3, "rating": 71.48 }]
I want the list to be sorted by the values in the rating key. How do I accomplish this?
Use operator.itemgetter as the key:
sorted(teamlist, key=operator.itemgetter('rating'))
You can use the sorted function with a sorting key referring to whichever field you wish.
teamlist_sorted = sorted(teamlist, key=lambda x: x['rating'])
from operator import itemgetter
newlist = sorted(team_list, key=itemgetter('rating'))