0

Scenario: A dictionary contains many lists that I want to extract. Psuedocode: E.g.

Dict = {'a':[1,2,3], 'b':[2,3,4], 'c':[4,5,6]}

Result, I want to create an array named after the keys in a for loop. Is it possible? I want a = [1,2,3], b = [2,3,4], c=[4, 5, 6] without having to type the a = [], b = [], c = [] and append them individually, is there anyway to do this in a for loop automatically?

Result:

a = [1,2,3]
b = [2,3,4]
c = [4,5,6]

My current solution: Create a class

class Container:
     def __init__(self):
         self.k = []
result = [Container() for i in range(4)]
for i,k in enumerate(Dict.keys()):
    result[i] = Dict[k]

Is there any faster solution?

1
  • 1
    TLDR of the duplicate: You can use globals().update(Dict) but please reconsider whether you really should. Commented Sep 17, 2021 at 8:56

1 Answer 1

1

You can use exec, but note that this is a possible security risk and not recommended:

Dict = {'a':[1,2,3], 'b':[2,3,4], 'c':[4,5,6]}

for k,v in Dict.items():
    exec(k+" = v")

Edit:

The security risk is basically somebody putting code into Dict and thereby trying to get it executed. A harmless test you could make is to add d:os.getcwd() to Dict, hoping that the program already imports os, then you'll later have a variable d with your working directory. You could for example use something like this to read file contents and send them to somebody else. A more malign user could try to execute code that removes certain files from your hard disk, or installs trojans, etc. To be honest I did not manage to do really malign things while giving it a short try, because naively doing things like d:import os; print("Hello world") lead to a syntax error, but there most likely are ways to do bad stuff using some libraries I did not think of (or other tricks). For a better read, I'd refer to this question and the links in the first answer.

Sign up to request clarification or add additional context in comments.

8 Comments

Could you elaborate the risk involved?
@elpsyCongroo: If outside code or data can change the dictionary keys then k could end up being something like 'format-hard-disk(); x'. Basically this: xkcd.com/327
Ah yeah, good old Bobby tables, didn't even have to look that one up. ;)
But getting access to the Dict on my computer requires access to my computer right? So Once I restarted my Python console, the Dict is deleted, right?
That is correct, as long as you remain in sole and full control of Dict, this is safe. It becomes dangerous if you read in something from files somebody as access to, or if you use some other API and fill Dict with something from the internet, for example, or in open-source projects where somebody might inject code that you didn't review thoroughly.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.