简体   繁体   English

在Django字典中删除具有空值的项目

[英]Remove item with empty value in django dictionary

I want to remove dictionary item on my list. 我想删除列表中的词典项目。

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

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

What should I do to achieve the result below: 我应该怎么做才能达到以下结果:

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

Just use a dict comprehension : 只需使用dict理解即可

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

or using a for loop: 或使用for循环:

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

too easy just do this 太容易了,只是这样做

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

hope it helps : ) 希望能帮助到你 : )

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

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