在django字典中删除空值的项目

时间:2017-10-10 06:32:46

标签: python django dictionary

我想删除列表中的字典项。

Animals = ['dog', 'cat', 'fish', 'goat']
Owner = ['Nash', 'Luffy', '', '']

C = dict(zip(Animals, Owner))
C = {'dog':'Nash', 'cat':'Luffy', 'fish':'', 'goat':''}

我应该怎样做才能达到以下结果:

C =  {'dog':'Nash', 'cat':'Luffy'}

2 个答案:

答案 0 :(得分:2)

只需使用dict comprehension

>>> {k: v for k, v in C.items() if v != ''}
{'dog': 'Nash', 'cat': 'Luffy'}

或使用for循环:

for k, v in C.items():
    if v == '':
        del(C[k])

答案 1 :(得分:-2)

这样做太容易了

mylist = {}
count = 0
for i in animals:
    mylist[i] = owner[count]
    count += 1

希望它有所帮助:)

相关问题