Python - append JSON into main branch - python

Maybe I am too stuck to see the simple solution for the following problem:
Given:
import json
a = {
"24631331976_defa3bb61f_k.jpg668058":{
"regions": {
"0": {},
"1": {}
}
}
}
b = {
"16335852991_f55de7958d_k.jpg1767935":{
"regions": {
"0": {}
}
}
}
I want to append them in order to get the following output.
enter image description here
Thanks to Daniel Hepper and SegFault, the problem could be solved with:
a.update(b)

c = {}
c.update(a)
c.update(b)
Alternatively, if you are fine with modifying a:
a.update(b)
Note that your code uses Python dictionaries, not JSON strings.

You cannot 'append' a dict to another one, simply because the append add element to the end of an ordered list of elements.
dicts don't have the notion of order, fist or last element. Thus no append for dict.
The action you want to do is merging two dicts, and you can do that using the update method defined for the dict type.
a.update(b)
PS: that will modify the dict a

Related

Create dictionary with a for loop

I want to create a dictionary with Key value pairs which are filled via an for Loop
The dictionary I want to achive
[
{
"timestamp": 123123123,
"image": "image/test1.png"
},
{
"timestamp": 0384030434,
"image": "image/test2.png"
}
]
My code does not work and I´m new to the datatypes of python.
images_dict = []
for i in images:
time = Image.open(i)._getexif()[36867]
images_dict = {"timestamp": time, "image": i}
What am I missing?
First, you seem to be confusing the definition of a list and a dictionary in python. Dictionaries use curly brackets {} and lists use regular brackets []. So in your first example, you are describing a list with a single element, which is a dictionary.
As for your code example, you are creating an empty list, and then iterating over images which I assume is a list of images, and then redefining the variable images_dict to be a dictionary with two key: value pairs for every iteration.
It seems like what you want is this:
images_dict = []
for image in images:
time = Image.open(1)._getexif()[36867]
images_dict.append({'timestamp': time, 'image': image})
The answer from Tom McLean worked for me, I´m a little bit confused with the dataypes of python
images_dict.append({"timestamp": time, "image": i})

How can I read from a list to get a dict?

I am getting an error I have never seen before, and there isn't great information on the internet on how to fix this that I could understand.
embed.add_field(name=f"Departure Airport ({res['departure']['airport']['icao']})")
The Error:
TypeError: list indices must be integers or slices, not str
JSON Response: https://mystb.in/NeverSmiliesTowers.json
I understand that I am trying to read the list as a dict, but I am not so sure how to get a dict from a list. Hope you understand my issue.
Note: res is just res = await foo.json(). It just formats the response in JSON.
I am also not reading this from a local file. I am reading this from an API response.
There is a common misconception that JSONs always represent dictionaries at their top level. They can represent lists as well at the top level. These are both valid JSONs:
{
"a": "foo",
"b": ["bar", "baz"]
}
[
{
"a1": "foo1",
"b1": ["bar1", "baz1"]
},
{
"a2": "foo2",
"b2": ["bar2", "baz2"]
}
[
The JSON sample you provided matches the second snippet above, where the top-level structure is a list(-like). Notice how the JSON begins with an opening square-bracket:
[
{
"greatCircleDistance":{
...
The res JSON is a list of dictionaries, so you need to retrieve the first dictionary from this list.
You can do so with:
res[0]['departure']['airport']['icao']
(notice how we first index the res list, which returns a dictionary that we can then get the 'departure' from.)
The response is a list, not a dict. You need to first access that list and then all the dict keys
res[0]['departure']['airport']['icao']

Nested dictionary access is returning a list

The issue I'm having is that when i try to access the values within a nested dictionary, i cannot because it's returning a list instead of a dictionary.
I have a .json file with this format;
{
"users": [
{
"1": {
"1": "value",
"2": "value"
}
}
]
}
I load the .json file, and access the value i want by using this function
def load_json(fn):
with open(fn) as pf:
data = json.load(pf)
return data['users']['1']['2']
If i simply do return data it is a dictionary, but if try to access further by adding ['users'], it turns into a list and will give an index error if i try to access key #1 or #2 inside of that..
My objective is to obtain the value of the nested key #2 for example, ideally without having loop through it.
Your JSON contains an array (Python list) wrapping the inner dicts (that's what the [ and ] in your JSON indicate). All you need to do is change:
return data['users']['1']['2']
to:
return data['users'][0]['1']['2']
# ^^^ Added
to index the list to get into the inner dicts.
given your data structure, and following it down :
data is a dictionary - with one key 'users' and a value of a list
data['users'] is a list - with one entry
data['users'][0] is a dictionary - with one key '1' and a value of a dictionary
data['users'][0][1] is a dictionary - with two keys '1' and '2'
So you need to do do :
def load_json(fn):
with open(fn) as pf:
data = json.load(pf)
return data['users'][0]['1']['2']

How to properly keep structure when removing keys in JSON using python?

I'm using this as a reference: Elegant way to remove fields from nested dictionaries
I have a large number of JSON-formatted data here and we've determined a list of unnecessary keys (and all their underlying values) that we can remove.
I'm a bit new to working with JSON and Python specifically (mostly did sysadmin work) and initially thought it was just a plain dictionary of dictionaries. While some of the data looks like that, several more pieces of data consists of dictionaries of lists, which can furthermore contain more lists or dictionaries with no specific pattern.
The idea is to keep the data identical EXCEPT for the specified keys and associated values.
Test Data:
to_be_removed = ['leecher_here']
easy_modo =
{
'hello_wold':'konnichiwa sekai',
'leeching_forbidden':'wanpan kinshi',
'leecher_here':'nushiyowa'
}
lunatic_modo =
{
'hello_wold':
{'
leecher_here':'nushiyowa','goodbye_world':'aokigahara'
},
'leeching_forbidden':'wanpan kinshi',
'leecher_here':'nushiyowa',
'something_inside':
{
'hello_wold':'konnichiwa sekai',
'leeching_forbidden':'wanpan kinshi',
'leecher_here':'nushiyowa'
},
'list_o_dicts':
[
{
'hello_wold':'konnichiwa sekai',
'leeching_forbidden':'wanpan kinshi',
'leecher_here':'nushiyowa'
}
]
}
Obviously, the original question posted there isn't accounting for lists.
My code, modified appropriately to work with my requirements.
from copy import deepcopy
def remove_key(json,trash):
"""
<snip>
"""
keys_set = set(trash)
modified_dict = {}
if isinstance(json,dict):
for key, value in json.items():
if key not in keys_set:
if isinstance(value, dict):
modified_dict[key] = remove_key(value, keys_set)
elif isinstance(value,list):
for ele in value:
modified_dict[key] = remove_key(ele,trash)
else:
modified_dict[key] = deepcopy(value)
return modified_dict
I'm sure something's messing with the structure since it doesn't pass the test I wrote since the expected data is exactly the same, minus the removed keys. The test shows that, yes it's properly removing the data but for the parts where it's supposed to be a list of dictionaries, it's only getting returned as a dictionary instead which will have unfortunate implications down the line.
I'm sure it's because the function returns a dictionary but I don't know to proceed from here in order to maintain the structure.
At this point, I'm needing help on what I could have overlooked.
When you go through your json file, you only need to determine whether it is a list, a dict or neither. Here is a recursive way to modify your input dict in place:
def remove_key(d, trash=None):
if not trash: trash = []
if isinstance(d,dict):
keys = [k for k in d]
for key in keys:
if any(key==s for s in trash):
del d[key]
for value in d.values():
remove_key(value, trash)
elif isinstance(d,list):
for value in d:
remove_key(value, trash)
remove_key(lunatic_modo,to_be_removed)
remove_key(easy_modo,to_be_removed)
Result:
{
"hello_wold": {
"goodbye_world": "aokigahara"
},
"leeching_forbidden": "wanpan kinshi",
"something_inside": {
"hello_wold": "konnichiwa sekai",
"leeching_forbidden": "wanpan kinshi"
},
"list_o_dicts": [
{
"hello_wold": "konnichiwa sekai",
"leeching_forbidden": "wanpan kinshi"
}
]
}
{
"hello_wold": "konnichiwa sekai",
"leeching_forbidden": "wanpan kinshi"
}

Deleting a key from a dictionary that is in a list of dictionaries

I have a list of dictionaries generated by:
r=requests.get(url, headers={key:password})
import_data_list.append(r.json())
I want to delete the first key from these dictionaries. I know I can delete the dictionaries in the list with:
del import_data_list[0]
But how do I delete a key from the dictionary in the list, rather than deleting the whole dictionary.
I tried something like:
del import_data_list[0["KEY"]]
Obviously it doesnt work!
Any help would be much appreciated and sorry if its a dumb question. Still learning!
If you want to delete the first key (you don't know its name, you just know it is the first one) from these dictionaries, I suggest you to loop over the dictionaries of the list. You can use list(d.keys())[0] or even list(d)[0] to get the first key of a dictionary called d.
Here is an example:
for d in import_data_list:
k = list(d)[0] # get the first key
del d[k] # delete it from the dictionary
print(import_data_list)
You can also do it with one-lined style using a list comprehension, which I find quite smart too. In this case you also retrieve the values of the first keys in a list, which might be useful:
r = [d.pop(list(d)[0]) for d in import_data_list]
print(import_data_list)
Note that it works only with python version >= 3.6 (but not with version <= 3.5 because dictionaries are not ordered)
Assume you have this list of dictionaries.
myList = [
{
"Sub1List1" : "value",
"Sub2List1" : "value",
"Sub3List1" : "value",
"Sub4List1" : "value"
},
{
"Sub1List2" : "value",
"Sub2List2" : "value",
"Sub3List2" : "value",
"Sub4List2" : "value"
},
{
"Sub1List3" : "value",
"Sub2List3" : "value",
"Sub3List3" : "value",
"Sub4List3" : "value"
}
]
Now, if you want to delete key Sub1List1 from the first list, you can do this by using :
del myList[0]["Sub1List1"]
Use the command:
del dictionaryName[KEY]

Categories

Resources