json_response appended to dictionary - for loop dictionary is None [duplicate] - python

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Why doesn't a python dict.update() return the object?
(11 answers)
Closed 7 days ago.
I have such a code using a for loop in order to append the json_response to a dictionary:
d = {}
for x in range(0,8):
gte = date_list[x].strftime("%Y-%m-%dT%H:%M:%S")
lte = date_list[x+1].strftime("%Y-%m-%dT%H:%M:%S")
url = 'https://abcxyz'
headers = {'Content-type': 'application/json'}
body={xyz}
y = json.dumps(body)
response = requests.get(url,proxies=proxies, timeout=30, auth=HTTPBasicAuth('auth', 'xyz'), headers=headers, data=y)
json_response = response.json()
dic = d.copy()
dic = dic.update(json_response)
print(dic)
The code is working. I get a json_response. What is not working seems to be the line dic = dic.update(json_response). But I do get None back. What did I do wrong here? I would like to get my json_response appended to a dictionary in order to read my data in as pandas dataframe...

Related

Delete lists with same elements in this case words in a listbut in different order in Python [duplicate]

This question already has answers here:
Remove duplicated lists in list of lists in Python
(4 answers)
Closed 7 months ago.
I have this list for example but there are more elements in the problem
data = [['USD','PEN'], ['GFY' ,'ARG'], ['TFG','RSD'], ['PEN','USD'], ['GFT','RSD']]
How can I eliminate the elements of the list that are repeated but in a different order, in this case the ['PEN','USD'] would be eliminated because the ['USD','PEN'] already exists in Python
The idea is that we can check the existence by the sorted element.
You can achieve this like below.
You could make this more elegant.
data = [['USD','PEN'], ['GFY' ,'ARG'], ['TFG','RSD'], ['PEN','USD'], ['GFT','RSD']]
tmp = []
exists = set()
for x in data:
x_sorted = tuple(sorted(x))
if x_sorted not in exists:
tmp.append(x)
exists.add(x_sorted)
tmp
# [['USD', 'PEN'], ['GFY', 'ARG'], ['TFG', 'RSD'], ['GFT', 'RSD']]
data = [['USD', 'PEN'], ['GFY', 'ARG'], ['TFG', 'RSD'], ['PEN', 'USD'], ['GFT', 'RSD']]
def remove_entries(data, entry1, entry2): # define function
for entry in data: # for every entry in the list
if entry1 in entry and entry2 in entry: # if both entries are present
data.remove(entry) # remove
return data # return result
clear = remove_entries(data, "USD", "PEN")
print(clear)

How to get content of each of the multiple function returns in Python? [duplicate]

This question already has answers here:
Ignore python multiple return value
(12 answers)
Closed 8 months ago.
Suppose we have a function abc where it returns four dicts after some processing as shown. For future if I will only need one tuple from the four, how to get it?
Eg., I only want dict d_two which function abc returns or content of each of the four returns?
def abc():
d_one = dict()
d_two = dict()
d_three = dict()
d_four = dict()
.
.
.
.
return (d_one, d_two, d_three, d_four)
You would need to deconstruct the returned value. There are multiple ways of doing this.
I should also note that dict() doesn't create tuples it creates dictionaries, but the process would be the same for both.
Here are some examples
_, d_two, _, _ = abc()
# or
d_two = abc()[1]
# or
dicts = abc()
d_two = dicts[1]

Dictionary Conversion [duplicate]

This question already has answers here:
How to reverse a dictionary that has repeated values
(7 answers)
Closed 1 year ago.
I got an python interview question:
#Dictionary
Convert
i = {"volvo":"car", "benz":"car", "yamaha":"bike", "hero":"bike"}
in to
output = {"car":["volvo", "benz"], "bike":["yamaha", "hero"]}
You can use the try/except process to reorder the dictionary.
i = {"volvo":"car", "benz":"car", "yamaha":"bike", "hero":"bike"}
output ={}
for k, it in i.items():
try:
output[it].append(k)
except KeyError:
output[it] = [k]
print(output)
Output:
{'car': ['volvo', 'benz'], 'bike': ['yamaha', 'hero']}

Cannot append a list of dictionaries in a python list [duplicate]

This question already has answers here:
Creating a list of dictionaries results in a list of copies of the same dictionary
(4 answers)
Closed 4 years ago.
I am trying to ouptut a list of dicts with unique user IDs. I am using the following code to achieve this:
import json
import random
import string
def random_string_generator(size=15, chars=string.ascii_uppercase + string.digits):
return '#' + ''.join(random.choice(chars) for _ in range(size))
list_users = ['user_id'] * 5
data = {}
list_json = []
for user in list_users:
data['user_id'] = random_string_generator() # function to generate a unique key
list_json.append(data)
print(list_json)
However, my code output is giving the following:
[{'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}, {'user_id': '#J1FTZ3TLOITMVW6'}]
I would like to know why the list is filled with the same item over and over again?
Because you append dict over and over again with the same key user_id.
So you've got list of dictionaries.

How to Combine two JSON files? [duplicate]

This question already has answers here:
How can I add new keys to a dictionary?
(19 answers)
Closed 5 years ago.
I've two json objects, I 'm figuring out a way on how to merge them in python
y={"success":"true"}
x={"0":"740","1":"747","2":"883","3":"750","4":"769"}
I need the final result in the following manner
{"success":"true",
"data":{
"0":"740",
"1":"747",
"2":"883",
"3":"750",
"4":"769"
}
}
I am trying to append it, but its showing some error. Help me with the code in python.
your input seem to be strings and not dictionaries. you need to convert them to dicts using json.loads:
import json
y = '{"success":"true"}'
x = '{"0":"740","1":"747","2":"883","3":"750","4":"769"}'
res = json.loads(y)
res['data'] = json.loads(x)
print(res)
if you need the output as string again, use json.dumps:
res_str = json.dumps(res)
if you insist on having the ouput sorted:
res_str = json.dumps(res, sort_keys=True)
You can simply do y["data"] = x
y={"success":"true"}
x={"0":"740","1":"747","2":"883","3":"750","4":"769"}
y["data"] = x
I assume that they are strings and not python dicts. So here is what you can do
y='{"success":"true"}'
x='{"0":"740","1":"747","2":"883","3":"750","4":"769"}'
import json
dict1 = json.loads(x)
dict2 = json.loads(y)
dict2['data'] = dict1
result = json.dumps(dict2)
print result
The code above gives you this
{"data": {"1": "747", "0": "740", "3": "750", "2": "883", "4": "769"}, "success": "true"}
If you want to have the structure in the json string preserved you can look into this link. That will make the decoding a little bit more complex.

Categories