python one liner code for two nested for loop
python, python-2.7
Solution
lst=[{'applicationName': "ATM Monitoring",
'roamingDrop': "",
'noOfCustomer': None,
'ipAddress': "192.168.1.1",
'url': "www.google.co.in",},
{'applicationName': None,
'roamingDrop': "",
'noOfCustomer': None,
'ipAddress': "192.168.1.1",
'url': "www.google.co.in",}]
print [{key: val if val else "" for key, val in dct.items()} for dct in lst]
explained:
dct = lst[0]
{'applicationName': "ATM Monitoring",
'roamingDrop': "",
'noOfCustomer': None,
'ipAddress': "192.168.1.1",
'url': "www.google.co.in",}
Using dictionary comprehension (available since Python 2.7), first just reconstructing the dictionary into the same value:
{key: val for dct.items()}
and extending it by assigning "" in case, we have as original value None (or any other value evaluating to False)
{key: val if val else "" for dct.items()}
Finally (as shown above) it is applied in enveloping list comprehension to all items in the list.
{key: val for dct.items()}
Strictly speaking, this replaces anything, what looks as boolean False by "".
If we want only `None` values replaced by `""`, and e.g. `False` and `0` keep as it is, we shall e more strict:
print [{key: val if val is not None else "" for key, val in dct.items()} for dct in lst]
Problem
How to get the desired result in python one liner ?? ``` object_list=[{'applicationName': "ATM Monitoring", 'roamingDrop': "", 'noOfCustomer': None, 'ipAddress': "192.168.1.1", 'url': "www.google.co.in",}, {'applicationName': None, 'roamingDrop': "", 'noOfCustomer': None, 'ipAddress': "192.168.1.1", 'url': "www.google.co.in",}] ``` Result required is to replace all None to "" ``` object_list=[{'applicationName': "ATM Monitoring", 'roamingDrop': "", 'noOfCustomer': "", 'ipAddress': "192.168.1.1", 'url': "www.google.co.in",}, {'applicationName': "", 'roamingDrop': "", 'noOfCustomer': "", 'ipAddress': "192.168.1.1", 'url': "www.google.co.in",}] ``` Simple Function to make this happens is : ``` def simple(): for object in object_list: for key, value in object.iteritems(): if value: dict( object, **{key: value}) else: dict(object, **{key: ''}) ``` And Python one unsuccessful one liner: ``` [dict(object, **{key: value}) if value else dict(object, **{key: ''}) for object in object_list for key, value in object.iteritems()] ``` Can the one liner be achieved with list comprehensions?