【问题标题】:Build dictionary in python在python中构建字典
【发布时间】:2020-05-02 15:08:30
【问题描述】:

Php 足够聪明,可以让我在构建关联数组时做这样的事情...

while ($row = $mysql_result->fetch_assoc())
{
  $array[$row['ip']][$row['slot']] = '';
}

...每个 IP 将有 X 个 IP 和 X 个插槽。我可以根据需要即时创建新键和其他关联数组。

python 有类似的功能吗?在构建字典时,我似乎无法做类似的事情......

rows = cur.fetchall()
host_list = {}
for row in rows:
  host_list[row['ip']][row['slot']] = ''

...因为我得到这样的东西:KeyError: '192.168.1.101'

我是否必须这样做,我必须一直检查密钥是否存在,如果不存在则创建它...

rows = cur.fetchall()
host_list = {}
for row in rows:
  if row['ip'] not in host_list.keys():
    host_list[row['ip']] = {}
  host_list[row['ip']][row['slot']] = ''

...或者有更好的方法吗?

【问题讨论】:

  • 你的方法很好。您还可以在常规字典上使用 defaultdictsetdefault 方法。注意,不要使用.keys() 来检查一个键是否在字典中,你可以使用some_key in some_dict
  • 您使用cur.fetchall() 获取哪些列?我之所以这么问,是因为如果你用 for ip, slot in rows: 之类的东西来迭代 rows,代码会变得更简洁。
  • 同意清洁度acdias,但我只是希望它清楚简洁地说明正在发生的事情。做你所说的事情我不需要做这样的事情:ip = row['ip']

标签: python


【解决方案1】:

您可以使用defaultdict

from collections import defaultdict

hostlist = defaultdict(dict)
for row in rows:
  host_list[row['ip']][row['slot']] = ''

【讨论】:

  • 我正要提出同样的建议,但你的速度更快。 :-)
  • 关于同一脚本的后续行动。我正在做这样的事情: data[ip][oid_label] = str(value) 工作正常,但是当我深入另一层并尝试做这样的事情时: data[ip][slot][oid_label] = str(value) 我得到一个 KeyError。想法?
猜你喜欢
  • 1970-01-01
  • 2014-02-14
  • 2017-09-04
  • 2015-09-25
  • 2019-08-07
  • 2013-10-07
  • 2021-07-05
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多