-1

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.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
dipl0
  • 1,017
  • 2
  • 13
  • 36
  • 2
    i cannot reproduce this. please provide a [mcve]. Don't silence the exception either, provide the full error message including the stack trace – juanpa.arrivillaga Aug 10 '19 at 22:04

2 Answers2

1
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']}

Thalish Sajeed
  • 1,351
  • 11
  • 25
0

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()?

wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29
  • 1
    they are apparently already trying to use `ast.literal_eval` and it is failing. – juanpa.arrivillaga Aug 10 '19 at 22:04
  • Additionally `eval` is highly not recommended, and it is recommended to use `literal_eval` instead, which OP is already using, which **you** state in your answer. So, why is your answer to use `eval`? – Tomerikoo Aug 10 '19 at 22:32