Home > other >  Create multiple dictionaries in an efficient way
Create multiple dictionaries in an efficient way

Time:03-06

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
}

CodePudding user response:

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

CodePudding user response:

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.

  • Related