本文介绍了迭代字典和列表的python方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,其中包含一些列表和一些字典,如下所示.

I have a dict which contains some lists and some dicts, as illustrated below.

迭代dict并打印出每个顶级dict键的名称和地址对的最有效方式是什么?

What is the most pythonic way to iterate over the dict and print out the name and address pairs for each top level dict key?

谢谢

{
    'Resent-Bcc': [],
    'Delivered-To': [],
    'From': {'Name': 'Steve Watson', 'Address': '[email protected]'},
    'Cc': [],
    'Resent-Cc': [],
    'Bcc': [ {'Name': 'Daryl Hurstbridge', 'Address': '[email protected]'},
             {'Name': 'Sally Hervorth', 'Address': '[email protected]'},
             {'Name': 'Mike Merry', 'Address': '[email protected]'},
             {'Name': 'Jenny Callisto', 'Address': '[email protected]'}
           ],
    'To': {'Name': 'Darius Jedburgh', 'Address': '[email protected]'}
}

推荐答案

一种方法是将单独的dict更改为包含该dict的列表.然后所有条目都可以被视为相同

One way is to change the lone dicts into a list containing the dict. Then all the entries can be treated the same

>>> D = {
...     'Resent-Bcc': [],
...     'Delivered-To': [],
...     'From': {'Name': 'Steve Watson', 'Address': '[email protected]'},
...     'Cc': [],
...     'Resent-Cc': [],
...     'Bcc': [ {'Name': 'Daryl Hurstbridge', 'Address': '[email protected]'},
...              {'Name': 'Sally Hervorth', 'Address': '[email protected]'},
...              {'Name': 'Mike Merry', 'Address': '[email protected]'},
...              {'Name': 'Jenny Callisto', 'Address': '[email protected]'}
...            ],
...     'To': {'Name': 'Darius Jedburgh', 'Address': '[email protected]'}
... }
>>> L = [v if type(v) is list else [v] for v in D.values()]
>>> [(d["Name"], d["Address"]) for item in L for d in item ]
[('Steve Watson', '[email protected]'), ('Daryl Hurstbridge', '[email protected]'), ('Sally Hervorth', '[email protected]'), ('Mike Merry', '[email protected]'), ('Jenny Callisto', '[email protected]'), ('Darius Jedburgh', '[email protected]')]

或者是一个班轮版本

[(d["Name"], d["Address"]) for item in (v if type(v) is list else [v] for v in D.values())]

这篇关于迭代字典和列表的python方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:20