繁体   English   中英

如何访问包含另一个词典和列表的嵌套词典中的单个项目,并打印这些项目?

[英]How to access individual items in a nested dictionary that contains another dictionary and a list, and print the items?

我创建了一个字典,如下所示:

DictItems = {
             'Rule1' : {1 : [S1, S2, S3], 2 : [S4, S5], 3: [S8]},
             'Rule2' : {1 : [S2, S3], 2 : [S2, S4, S5]}
            }

我尝试了以下方法:

for key, value, listval in DictItems.items():
   print key, value, listval

但是它显示了错误:“ ValueError: need more than 2 values to unpack ”。

如何访问单个项目以进行打印操作

单个项目表示:我想检查关联规则。 因此,我想在if条件下访问单个项,例如“ Rule1”,然后检查下一个词典中的值,例如1或2,以及列表项。

我认为您过于复杂了。

鉴于此命令:

>>> DictItems = {
...              'Rule1' : {1 : ['S1', 'S2', 'S3'], 2 : ['S4', 'S5'], 3: ['S8']},
...              'Rule2' : {1 : ['S2', 'S3'], 2 : ['S2', 'S4', 'S5']}
...             }

您可以在一组或多组括号(成对的括号: []是AKA 订阅__getitem__运算符 )中使用键(用于dict)或索引(用于序列)访问单个元素:

>>> DictItems['Rule1']
{1: ['S1', 'S2', 'S3'], 2: ['S4', 'S5'], 3: ['S8']}
>>> DictItems['Rule1'][1]
['S1', 'S2', 'S3']
>>> DictItems['Rule1'][1][-1]
'S3'
>>> DictItems['Rule1'][1][-1][0]
'S'

剖析那里的最后一个:

 DictItems['Rule1'][1][-1][0]
             ^^^                   key to the top dict
                    ^              key to dict with int key
                       ^^          relative index to a sequence -- last one
                           ^       absolute index to a sequence -- first item

然后打印:

>>> for k, li in DictItems['Rule1'].items():
...    print k, li
... 
1 ['S1', 'S2', 'S3']
2 ['S4', 'S5']
3 ['S8']

例如,要访问和比较:

>>> DictItems['Rule1'][1][2]==DictItems['Rule2'][1][-1]
True

如果要解压缩示例,请使用嵌套循环:

>>> for k in DictItems:
...    for sk, li in DictItems[k].items():
...       print k, sk, li
... 
Rule2 1 ['S2', 'S3']
Rule2 2 ['S2', 'S4', 'S5']
Rule1 1 ['S1', 'S2', 'S3']
Rule1 2 ['S4', 'S5']
Rule1 3 ['S8']

由于字典是无序的,因此项目不一定按插入顺序排序。 您可以对键进行排序:

>>> for k in sorted(DictItems):
...    for sk in sorted(DictItems[k]):
...       print k, sk, DictItems[k][sk]
... 
Rule1 1 ['S1', 'S2', 'S3']
Rule1 2 ['S4', 'S5']
Rule1 3 ['S8']
Rule2 1 ['S2', 'S3']
Rule2 2 ['S2', 'S4', 'S5'] 

您还可以使用json漂亮地打印嵌套字典:

>>> import json
>>> print json.dumps(DictItems, sort_keys=True, indent=4)
{
    "Rule1": {
        "1": [
            "S1", 
            "S2", 
            "S3"
        ], 
        "2": [
            "S4", 
            "S5"
        ], 
        "3": [
            "S8"
        ]
    }, 
    "Rule2": {
        "1": [
            "S2", 
            "S3"
        ], 
        "2": [
            "S2", 
            "S4", 
            "S5"
        ]
    }
}

dict.items()提供(key, value)对,并且不会进一步解压缩所包含的字典。

只能解压缩键和值,这里的值是另一个字典对象。 要进入嵌套字典,也可以对其进行迭代,也许是:

for rule, rule_mapping in DictItems.items():
    print rule
    for rulemap_number, listvalue in rule_mapping.items():
        print '{}: {}'.format(rulemap_number, listvalue)

要回答您的问题,您可以在原始循环中嵌套另一个循环,如下所示:

for key, value in DictItems.items():
   print key
   for key2, value2 in value.items():
       print key2, value2

依此类推,可以根据需要将级别降低到最低。 如果您想花哨的话,可以在那里进行所有递归,但只要两个级别就足够了。

注意 忽略我正在使用的不存在的命名约定

for rule_num, group in DictItems.items():
    print rule_num
    for index, lst in group.items():
        print "    %s: %s" % (index, lst)

...

Rule2
    1: ['S2', 'S3']
    2: ['S2', 'S4', 'S5']
Rule1
    1: ['S1', 'S2', 'S3']
    2: ['S4', 'S5']
    3: ['S8']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM