I have a Python dictionary
original_dict={'body': '{"infra":["dev4","elk"],{"type":"file_integrity"}'}
I want to be able to parse original_dict keys and values as a normal dictionary which I am not able to do now because 'body' key has a a dictionary casted as string and therefore I am not refer to any of it's keys. So I should be able to say:
infra=original_dict['body]['infra']
Can anyone help me out with this.
First of all, you are missing a curly brace in the original_dict.
Here is an example of converting a string into a dictionary.
import json
original_dict={'body':'{"infra":["dev4","elk"],"type":"file_integrity"}'}
original_dict['body'] = json.loads(original_dict['body'])
infra=original_dict['body']['infra']
print(infra)
Output : ['dev4', 'elk']
You can use ast too:)
import ast
original_dict = {'body': '{"infra":["dev4","elk"],"type":"file_integrity"}'}
original_dict['body'] = ast.literal_eval(original_dict['body'])
Related
in python I have:
dict = {}
dict['test'] = 'test'
when I print I get:
{'test':'test'}
How can I make it like this:
{"test":"test"}
Please Note, replace won't work as test may be test't...
I tried:
dict = {}
dict["test"] = "test"
You can use json.dumps()
For example, if you use print json.dumps(dict) you should get the desired output.
Additionally, as suggested in a different related question, you may construct your own version of a dict with special printing:
How to create a Python dictionary with double quotes as default quote format?
I try to convert this String to only the link: {"link":"https://i.imgur.com/zfxsqlk.png"}
I'm trying to create a discord bot, which sends random pictures from the API https://some-random-api.ml/img/red_panda.
With imageURL = json.loads(requests.get(redpandaurl).content) I get the json String, but what do I have to do that I only get the Link like this https://i.imgur.com/zfxsqlk.png
Sorry if my question is confusingly written, I'm new to programming and don't really know how to describe this problem.
You can simply do this:
image_url = requests.get(your_api_url).json()["link"]
Directly use requests.json(), no need to load the string with json.loads and other manual stuff.
What you get from json.loads() is a Python dict. You can access values in the dict by specifying their keys.
In your case, there is only one key-value pair in the dict: "link" is the key and "https://i.imgur.com/zfxsqlk.png" is the value. You can get the link and store it in the value by appending ["link"] to your line of code:
imageURL = json.loads(requests.get(redpandaurl).content)["link"]
I have an API that expects to receive the data in a string format. The data looks like this:
test = """{"API_name":"getScenario","token":"1112223333","clientId":"1","clientEmail":"yup#nope#gmail.com", "more": "hello"}"""
I am used to accessing the dictionary keys rather easily test[token] but in this case it is all encased in a multi-line string.
How is this supposed to be accessed?
Parse the string and then find access by key
import json
data = json.loads(test)
data['API_name']
I have a dictionary that each key is unicode and I'm using the following code to insert JSON file into a dictionary.
def readDictFromFile(filename):
my_file = Path(filename)
if my_file.is_file():
return json.load(codecs.open(filename,encoding='utf-8'))
return {}
But when I try to check if a string is in the dictionary, it does not work:
if title in dict:
continue
The reason is that the dict contains keys that look like: u'\u05d5. I say that I need to use repr (link) but is there a way to do it with the same syntax without looping for each key in the dict?
I am trying to remove certain items from a query string, the best way doing this would be to parse the query string, iterate over and remove the particular key I dont want and join it all back together.
Following the python guide, it seems the urlencode function they say to use, doesn't work as one would expect.
Fee the following code, which simply parses the query string, and then joins it back together. I've set it to keep the empty value.
>>> f = 'name=John%20Doe&seq=123412412412&wer'
>>> q = urlparse.parse_qs(f, keep_blank_values=True)
>>> q
{'wer': [''], 'name': ['John Doe'], 'seq': ['123412412412']}
>>> urllib.urlencode(q)
'wer=%5B%27%27%5D&name=%5B%27John+Doe%27%5D&seq=%5B%27123412412412%27%5D'
I am expecting the result of the query code, to be the same as the f string.
http://docs.python.org/2/library/urlparse.html#urlparse.parse_qs
Use the urllib.urlencode() function to convert such dictionaries into query strings.
So I assume I have to loop over the q variable and build the string manually, calling urlencode on each item of the dictionary? Isn't there a better way...
Using python 2.7
Thanks
You should use the doseq argument to urlencode since you have sequences in your query dict:
>>> urllib.urlencode(q, doseq=1)
'wer=&name=John+Doe&seq=123412412412'