追加到嵌套字典中存储的列表 [英] Appending to lists stored in a nested dictionary

查看:56
本文介绍了追加到嵌套字典中存储的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想创建一个像这样的字典:

If I want to create a dictionary that looks like this:

switches = {'s1': {'port1': [[0, 0, 0], [1, 1, 1]], 'port2': [2,2,2]}}

我尝试过:

switches = {}
switches['s1'] = {}
switches['s1']['port1'] = [0, 0, 0]
switches['s1']['port1'] = [1, 1, 1]
switches['s1']['port2'] = [2, 2, 2]

但是,[1, 1, 1]会覆盖[0, 0, 0]

如何为键'port1'取值[[0, 0, 0], [1, 1, 1]]?

推荐答案

扩展idjaw的评论和keksnicoh的答案,我认为您可以通过使用defaultdict使您的生活更加轻松.

Expanding on idjaw's comment and keksnicoh's answer, I think you can make your life a little bit easier by using a defaultdict.

>>> from collections import defaultdict
>>> d = defaultdict(lambda: defaultdict(list))
>>> d['s1']['port1'].append([0, 0, 0])
>>> d['s1']['port1'].append([1, 1, 1])
>>> d['s1']['port2'].append([2, 2, 2])
>>> d
defaultdict(<function <lambda> at 0x7f5d217e2b90>, {'s1': defaultdict(<type 'list'>, {'port2': [[2, 2, 2]], 'port1': [[0, 0, 0], [1, 1, 1]]})})

您可以像常规词典一样使用它:

You can use it just like a regular dictionary:

>>> d['s1']
defaultdict(<type 'list'>, {'port2': [[2, 2, 2]], 'port1': [[0, 0, 0], [1, 1, 1]]})
>>> d['s1']['port1']
[[0, 0, 0], [1, 1, 1]]

这篇关于追加到嵌套字典中存储的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆