英文:
How to remove unwanted fields from lists of dictionary in python using for loop
问题
[{
'field_name': 'mobile',
'field_value': '8888888822',
'type': 'primary'
}, {
'field_name': 'name',
'field_value': 'putta',
'type': 'primary'
}]
英文:
[{
'field_name': 'mobile',
'field_value': '8888888822',
'type': 'primary'
}, {
'field_name': 'name',
'field_value': 'putta',
'type': 'primary'
}, {
'field_name': 'job',
'field_value': 'Student',
'type': 'primary'
}, {
'field_name': 'place'
'field_value': 'xyz',
'type': 'primary'
}, {
'field_name': 'vilage',
'field_value': '',
'type': 'primary'
}]
This is my json here i need to get the length of the list, and this is returning 5.
now i need to leave job field and place field from the list length and also fields which are having empty values example vilage field i am able to read field_name or field value using lambda function but not both(lamda accept only one parameter) how to acheive this. thanks for inputs. expected output length= 2
答案1
得分: 1
以下是代码的翻译部分:
IIUC you want to leave out elements where `field_name` is `job` or `field_value` is `''`. This can be achieved in a loop:
input_list = [{
'field_name': 'mobile',
'field_value': '8888888822',
'type': 'primary'
}, {
'field_name': 'name',
'field_value': 'putta',
'type': 'primary'
}, {
'field_name': 'job',
'field_value': 'Student',
'type': 'primary'
}, {
'field_name': 'place',
'field_value': '',
'type': 'primary'
}, {
'field_name': 'vilage',
'field_value': '',
'type': 'primary'
}]
count = 0
for el in input_list:
if el.get('field_name', 'job') != 'job' and el.get('field_value', None):
count += 1
print(count)
Using get(..)
allows you to leave out elements that don't have field_name
or field_value
as key.
You can also achieve this with a comprehension:
len([el for el in input_list if el.get('field_name', 'job') != 'job' and el.get('field_value', None)])
英文:
IIUC you want to leave out elements where field_name
is job
or field_value
is ''
. This can be achieved in a loop:
input_list = [{
'field_name': 'mobile',
'field_value': '8888888822',
'type': 'primary'
}, {
'field_name': 'name',
'field_value': 'putta',
'type': 'primary'
}, {
'field_name': 'job',
'field_value': 'Student',
'type': 'primary'
}, {
'field_name': 'place',
'field_value': '',
'type': 'primary'
}, {
'field_name': 'vilage',
'field_value': '',
'type': 'primary'
}]
count = 0
for el in input_list:
if el.get('field_name', 'job') != 'job' and el.get('field_value', None):
count += 1
print(count)
Using get(..)
allows you to leave out elements that don't have field_name
or field_value
as key.
You can also achieve this with a comprehension:
len([el for el in input_list if el.get('field_name', 'job') != 'job' and el.get('field_value', None)])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论