高效创建多个词典

发布于 2025-01-11 21:18:54 字数 231 浏览 0 评论 0原文

我必须创建10多个词典。有没有更有效的方法来使用Python的内置库创建多个字典,如下所述:

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

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
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南…巷孤猫 2025-01-18 21:18:54

dict 内置函数将从关键字参数创建一个字典:

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

但是你可以使用整数作为关键字参数:

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

但是, dict 也将接受可迭代的键/值元组,在这种情况下,它们的键可能是整数

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

如果所有字典的键都相同,则可以使用 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}

但是,如果您的密钥不一致,使用也没有问题文字 {...} 构造函数。事实上,如果您想要效率,文字构造函数可能是最佳选择

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.

薄荷梦 2025-01-18 21:18:54

您可以使用一个简单的函数来创建新词典。看下面的代码:

func = lambda **kwargs: kwargs

my_dict = func(x="test", y=1, z=[1, 'test'])
  • 注意字典的键只能是字符串

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文