So in my python script I have the following dictionary, except it's listed in string form:
{'MSVCRT.dll': ['atoi'], 'KERNEL32.DLL': ['VirtualFree', 'ExitProcess', 'VirtualProtect', 'LoadLibraryA', 'VirtualAlloc', 'GetProcAddress'], 'SHLWAPI.dll': ['PathFileExistsA'], 'USER32.dll': ['wsprintfA']}
I however would like to have this code as a dictionary of lists, as it clearly is. I tried the following code in orderto attempt to convert the string:
try:
dictimports = ast.literal_eval(stris)
print(dictimports)
except:
print("dict convert failed")
However it hits the except everytime :(
So to reiterate, I would like the keys to be say 'KERNEL32.DLL', and then those keys to have the list as the contents of the values, so have a list with the values ['VirtualFree', 'ExitProcess', 'VirtualProtect', 'LoadLibraryA', 'VirtualAlloc', 'GetProcAddress'] in this instance.
stris = {'MSVCRT.dll': ['atoi'], 'KERNEL32.DLL': ['VirtualFree', 'ExitProcess', 'VirtualProtect', 'LoadLibraryA', 'VirtualAlloc', 'GetProcAddress'], 'SHLWAPI.dll': ['PathFileExistsA'], 'USER32.dll': ['wsprintfA']}
stris is a dictionary. what seems to be the problem?
type(stris)
dict
stris.keys()
dict_keys(['MSVCRT.dll', 'KERNEL32.DLL', 'SHLWAPI.dll', 'USER32.dll'])
if your stris is a string - in which case you'd have
stris = "{'MSVCRT.dll': ['atoi'], 'KERNEL32.DLL': ['VirtualFree', 'ExitProcess', 'VirtualProtect', 'LoadLibraryA', 'VirtualAlloc', 'GetProcAddress'], 'SHLWAPI.dll': ['PathFileExistsA'], 'USER32.dll': ['wsprintfA']}"
and you will convert it to a dict
ast.literal_eval(stris)
{'MSVCRT.dll': ['atoi'], 'KERNEL32.DLL': ['VirtualFree','ExitProcess','VirtualProtect','LoadLibraryA','VirtualAlloc',
'GetProcAddress'],'SHLWAPI.dll': ['PathFileExistsA'],'USER32.dll':['wsprintfA']}
You could use eval() to convert the string to a dict.
The expression argument is parsed and evaluated as a Python expression
eval(stris) will execute the executions given as string an in your case return the parsed dictionary.
But be aware of this: Using python's eval() vs. ast.literal_eval()?
Related
So I am struggling with getting a value from a JSON response. Looking in other post I have managed to write this code but when I try to search for the key (character_id) that I want in the dictionary python says that the key doesn't exist. My solution consists in getting the JSON object from the response, converting it into a string with json.dumps() and the converting it into a dictionary with json.loads(). Then I try to get 'character_id' from the dictionary but it doesn't exist. I am guessing it is related with the format of the dictionary but I have little to none experience in python. The code that makes the query and tries to get the values is this: (dataRequest is a fuction that makes the request and return the response from the api)
characterName = sys.argv[1];
response = dataRequest('http://census.daybreakgames.com/s:888/get/ps2:v2/character/?name.first_lower=' + characterName + '&c:show=character_id')
jsonString = json.dumps(response.json())
print(jsonString)
dic = json.loads(jsonString)
print(dic)
if 'character_id' in dic:
print(dic['character_id'])
The output of the code is:
{"character_list": [{"character_id": "5428662532301799649"}], "returned": 1}
{'character_list': [{'character_id': '5428662532301799649'}], 'returned': 1}
Welcome #Prieto! From what I can see, you probably don't need to serialize/de-serialize the JSON -- response.json() returns a python dictionary object already.
The issue is that you are looking for the 'character_id' key at the top-level of the dictionary, when it seems to be embedded inside another dictionary, that is inside a list. Try something like this:
#...omitted code
for char_obj in dic["character_list"]:
if "character_id" in char_obj:
print(char_obj["character_id"])
if your dic is like {"character_list": [{"character_id": "5428662532301799649"}], "returned": 1}
you get the value of character_id by
print(dic['character_list'][0][character_id])
The problem here is that you're trying to access a dictionary where the key is actually character_list.
What you need to do is to access the character_list value and iterate over or filter the character_id you want.
Like this:
print(jsonString)
dic = json.loads(jsonString)
print(dic)
character_information = dic['character_list'][0] # we access the character list and assume it is the first value
print(character_information["character_id"]) # this is your character id
The way I see it, the only hiccup with the code is this :
if 'character_id' in dic:
print(dic['character_id'])
The problem is that, the JSON file actually consists of actually 2 dictionaries , first is the main one, which has two keys, character_list and returned. There is a second sub-dictionary inside the array, which is the value for the key character_list.
So, what your code should actually look like is something like this:
for i in dic["character_list"]:
print(i["character_id"])
On a side-note, it will help to look at JSON file in this way :
{
"character_list": [
{
"character_id": "5428662532301799649"
}
],
"returned": 1
}
,where, elements enclosed in curly-brackets'{}' imply they are in a dictionary, whereas elements enclosed in curly-brackets'[]' imply they are in a list
I have to variables one="{}{}{}T{}:{}:{}" and two='2021,-10,-28,05,40,33' When i try to use print(one.format(two)) i am getting errors. IndexError: Replacement index 1 out of range for positional args tuple. guessing it is because the two variable is being seen as a string.
So I switched and tried to do the *args method.
for item in two:
item = str(item)
data[item] = ''
result = template.format(*data)
However if I switch two='2021,-10,-28,00,00,00.478' it fails because a dictionary is unique. so how do i get the first method to work or is there a better solution.
You should split the two into list and then unpack it with *
one="{}{}{}T{}:{}:{}"
two='2021,-10,-28,05,40,33'
print(one.format(*two.split(','))) # 2021-10-28T05:40:33
I currently have a python dictionary where the keys are strings representing URLs, and the values are also string URLs.
#socketio.on('blacklist', namespace='/update')
def add_to_blacklist(message):
stored_blacklist.clear()
for key, val in message.items():
stored_blacklist[key] = val
lookup = {'name':'blacklist'}
resp = patch_internal('blacklist', payload={"sites":stored_blacklist}, **lookup)
However there is an issue with how python is interpreting the insertions. For example:
stored_blacklist["example.com"] = "thankspython.edu"
My desired behavior is that stored_blacklist maps "example.com" to "thankspython.edu" like so:
{'example.com':'thankspython.edu'}
However, printing stored_blacklist gives me this instead:
{'example': {'com': 'thankspython.edu'}}
How could I get the desired behavior where a string with a period character in it could be read as a normal string instead of automatically creating some pseudo-JSON object?
What I want to achieve
value = 'a.b.c.d.e'
new_value = value.split('.')
new_value[-1] = F
''.join(new_value)
Now I would like to achieve this in one line. something like below
''.join(value[-1] = F in value.split('.'))
my above expression throws error because it is kind of wrong so is there a possible way to achieve this
Value should be "1.2.3.4.5" and join doesn't work for int. You should use new_value[-1]='10' instead.
''.join(value.split('.')[:-1]+['10'])
I am trying to convert a string to a dictionary with dict function, like this
import json
p = "{'id':'12589456'}"
d = dict(p)
print d['id']
But I get the following error
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Why does it fail? How can I fix this?
What you have is a string, but dict function can only iterate over tuples (key-value pairs) to construct a dictionary. See the examples given in the dict's documentation.
In this particular case, you can use ast.literal_eval to convert the string to the corresponding dict object, like this
>>> p = "{'id':'12589456'}"
>>> from ast import literal_eval
>>> d = literal_eval(p)
>>> d['id']
'12589456'
Since p is a string containing JSON (ish), you have to load it first to get back a Python dictionary. Then you can access items within it:
p = '{"id":"12589456"}'
d = json.loads(p)
print d["id"]
However, note that the value in p is not actually JSON; JSON demands (and the Python json module enforces) that strings are quoted with double-quotes, not single quotes. I've updated it in my example here, but depending on where you got your example from, you might have more to do.