访问嵌套字典中的数据?蟒蛇

时间:2020-06-13 18:27:14

标签: python variables

我从回复中得到以下数据。这似乎是一个命令。

例如,我可以访问“说明”。您能为我应该阅读的内容提供建议,以允许我访问“ tcp_options”位。我假设这是一个嵌套的字典。

expected

3 个答案:

答案 0 :(得分:0)

要在python中的嵌套字典中访问元素,如下所示:

thing = { "hi":{"hello":"bye"}}

您会写:

print(thing["hi"]["hello"])

这应该返回以下内容:

>>> print(thing["hi"]["hello"])
bye
>>> ...

希望这能回答您的问题!

答案 1 :(得分:0)

全部

首先,感谢您的投入。但事实证明我有点白痴。

'tcp_options"':

实际上里面有一个“,这就是我遇到错误的原因。我认为”是某种形式的神秘python伏都教徒。

对不起,谢谢大家。

edit :我的代码行:print(newRules ['tcp_options“'] ['destination_port_range'] ['min'])现在可以正常工作了。

答案 2 :(得分:0)

按其键值访问dict应该很好:

dd = {
  "description": "sftp",
  "icmp_options": 'null',
  "is_stateless": 'false',
  "protocol": "6",
  "source": "127.0.0.1/32",
  "source_type": "CIDR_BLOCK",
  "tcp_options": {
    "destination_port_range": 'null',
    "source_port_range": {
      "max": 5500,
      "min": 5500
    }
  },
  "udp_options": 'null'
  }

for key,value in dd.items():
    print(key,value)


print(dd["tcp_options"])

输出:

description sftp                                                                                                                                                             
source_type CIDR_BLOCK                                                                                                                                                       
protocol 6                                                                                                                                                                   
source 127.0.0.1/32                                                                                                                                                          
icmp_options null                                                                                                                                                            
tcp_options {'source_port_range': {'max': 5500, 'min': 5500}, 'destination_port_range': 'null'}                                                                              
is_stateless false                                                                                                                                                           
udp_options null                                                                                                                                                             
{'source_port_range': {'max': 5500, 'min': 5500}, 'destination_port_range': 'null'}