在python中定义嵌套字典

编程入门 行业动态 更新时间:2024-10-24 20:21:47
本文介绍了在python中定义嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在python中定义一个嵌套字典。我尝试了以下操作:

I want to define a nested dictionary in python. I tried the following:

keyword = 'MyTest' # Later I want to pull this iterating through a list key = 'test1' sections = dict(keyword={}) #This is clearly wrong but how do I get the string representation? sections[keyword][key] = 'Some value'

我可以这样做:

sections = {} sections[keyword] = {}

但是Pycharm中有一个警告,说可以通过字典标签进行定义。

But then there is a warning in the Pycharm saying it can be defined through dictionary label.

有人可以指出如何实现此目标吗?

Can someone point out how to achieve this?

推荐答案

keyword = 'MyTest' # Later I want to pull this iterating through a list key = 'test1' sections = {keyword: {}} sections[keyword][key] = 'Some value' print(sections) {'MyTest': {'test1': 'Some value'}}

dict(keyword = {})创建一个字符串为 keyword 的字典

dict(keyword={}) creates a dict with the string "keyword" as the key not the value of the variable keyword.

In [3]: dict(foo={}) Out[3]: {'foo': {}}

在哪里使用dict实际使用变量的值如上所述。

Where using a dict literal actually uses the value of the variable as above.

更多推荐

在python中定义嵌套字典

本文发布于:2023-11-12 03:41:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580408.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   字典   定义   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!