-1

Python:

dict = {"a":1, "b":12, "c":1000}

a = dict["a"]
b = dict["b"]
c = dict["c"]

print(a) -> 1
print(b) -> 12
print(c) -> 1000

What is the pythonic way to deconstruct a dictionary?

In Javascript you could do something like this const a,b,c = dict, but how would I do it in python?

ClickThisNick
  • 5,110
  • 9
  • 44
  • 69

1 Answers1

0

If you're trying to turn all of your dict keys into globals you can do so with a for loop:

dict = {"a":1, "b":12, "c":1000}

for k, v in dict.items():
    globals()[k] = v

>>>a
1
>>>b
12
>>>c
1000
Primusa
  • 13,136
  • 3
  • 33
  • 53
  • 1
    This is just a generally bad approach to this. – juanpa.arrivillaga Jan 14 '19 at 21:11
  • @juanpa.arrivillaga I understand that making dict keys into globals isn't a good idea. However how to do so was the question. I answered the question. – Primusa Jan 14 '19 at 21:15
  • Well, being pedantic about it, it wasn't *actually* the question. The question was how to do destructing assignment with a `dict` in Python, which Python doesn't support, and this doesn't really work equivalently (it only works in the global scope, for instance). – juanpa.arrivillaga Jan 14 '19 at 21:18
  • You can just set `locals()` or another scope dictionary if you want to use it in a different scope. Do you expect me to say that this is impossible or that this is bad practice even though it is possible to replicate this kind of behavior? – Primusa Jan 14 '19 at 21:25
  • No, you *cant* just change `dict` returned by `locals()`. It won't affect the local namespace. IOW, it is "read-only". And yes, sometimes, a better answer is just "don't do that", e.g. "How do I parse this HTML using regex?" -> "don't do that, use an actual html parser" – juanpa.arrivillaga Jan 14 '19 at 21:26
  • That's my bad on the `locals()` comment, my tests case with a function was referring to a var that was still globally defined. I still stand my my point that this problem isn't the equivalent of "How do I parse the HTML using regex?", since the "don't do that" part is here but not the "use an actual html parser" solution – Primusa Jan 14 '19 at 21:35