0

The following gives KeyErrors:

from datetime import datetime

a = "Some Text"
d = datetime.now()

def create_dict(*args):
   dict([(i, locals()[i]) for i in args])

create_dict(a, d)

instead of: {'a': 'Some Text', 'd': 04-06-2018}

Where is it going wrong?

reservoirinvest
  • 1,463
  • 2
  • 16
  • 32
  • have you checked the value of `d`? is it valid? Maybe you imported just `datetime` and not `datetime.datetime` so it would be `d = datetime.datetime.now()` – Michriko Apr 06 '18 at 17:25
  • 1
    Possible duplicate of [Python variables as keys to dict](https://stackoverflow.com/questions/3972872/python-variables-as-keys-to-dict) – pstatix Apr 06 '18 at 17:31
  • The value of d is correct. How can dictionary be created using variables declared outside the function, with variable names as the keys? – reservoirinvest Apr 06 '18 at 17:35
  • @reservoirinvest if you need to use the variables defined outside the function (global scope) inside the function (local scope) you need to define `global variable_name` inside the function as well and then you can use the variable – iam.Carrot Apr 06 '18 at 17:55
  • @iam sample code will be helpful. – reservoirinvest Apr 06 '18 at 18:13
  • @reservoirinvest I've posted an answer – iam.Carrot Apr 06 '18 at 18:28

1 Answers1

0

A nifty dictionary comprehension can be used.

To get all global scoped variables, you can simply do the below:

global_var = {key: globals()[key] for i in args for key in globals().keys() if i == globals()[key]}

To get all the local scoped variables, you can simply to the below:

local_var = {key: locals()[key] for i in args for key in locals().keys() if i == locals()[key]}

If you're using them together, make sure you add them in a single dict so that you avoid modifying the collection on which you're iterating

If you wana learn more about scopes in python refer to this

iam.Carrot
  • 4,976
  • 2
  • 24
  • 71