user18326231
user18326231

Reputation: 11

Create multiple dictionaries in an efficient way

I have to create more than 10 dictionaries. Is there a more efficient way to create multiple dictionaries using Python's built-in libraries as described below:

    dict1_1= {
    "value":100,
    "secondvalue":200,
    "thirdvalue":300
}
dict1_2= {
    "fixedvalue":290,
    "changedvalue":180,
    "novalue":0
}

Upvotes: 1

Views: 148

Answers (2)

snakecharmerb
snakecharmerb

Reputation: 55620

The dict builtin will create a dictionary from keyword arguments:

>>> dict(a=1, b=2)
{'a': 1, 'b': 2}

but you can use integers as keyword arguments:

>>> dict(a=1, 2=2)
  File "<stdin>", line 1
    dict(a=1, 2=2)
              ^^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

However, dict will also accept an iterable of key/value tuples, and in this case they keys may be integers

>>> dict([('a', 1), (2, 2)])
{'a': 1, 2: 2}

If your keys are the same for all dicts you can use zip:

>>> keys = ('a', 2)
>>> values = [(1, 2), (3, 4)]
>>> for vs in values:
...     print(dict(zip(keys, vs)))
... 
{'a': 1, 2: 2}
{'a': 3, 2: 4}

However, if your keys are not consistent, there's nothing wrong with using the literal {...} constructor. In fact, if it's efficiency that you want, the literal constructor may be the best choice.

Upvotes: 1

Eshaq
Eshaq

Reputation: 1

you can use a simple function to create new dictionaries. Look at the code below:

func = lambda **kwargs: kwargs

my_dict = func(x="test", y=1, z=[1, 'test'])
  • Note that the keys of dictionary can only be string

Upvotes: 0

Related Questions