python - 如果非空,则将字典的值写入列表中

标签 python python-3.x dictionary

我有以下字典:

dict = {
       'field1': ('foo','bar'), 
       'field2': ('spam',''),
       'field3': ['apples', 'oranges']
       }

我想将值写入列表中,但前提是非空:

list = ['foo', 'bar', 'apples', 'oranges']

我可以使用 dict.values() 这个吗?如何检查元组的第二个元素是否为非空?

最佳答案

您可以使用列表理解:

dic = {
   'field1': ('foo','bar'), 
   'field2': ('spam',''),
   'field3': ['apples', 'oranges']
   }
new_result = [i for b in dic.values() for i in b if all(b)]

输出:

['foo', 'bar', 'apples', 'oranges']

关于python - 如果非空,则将字典的值写入列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51116488/

相关文章:

python - 在 WRDS CRSP 查询中使用来自外部文件的 Python 字典值

python - Django 在模板中显示列表的内容

python - TKINTER 小部件的配置选项列表

python - 如何对字符串中的字符进行排序但只保留撇号

arrays - 在 Swift 中将 NSArray 转换为 Array 会对数组值产生 nil

python - 如何分组并根据总和过滤数据框?

python - 猴子修补套接字库以使用特定的网络接口(interface)

python - 如何在 matplotlib python 中设置确切的日期刻度

python - 跳到字典中的下一项

java - 使用 OpenStreetMaps JMapViewer 移动 map 标记