Printing dict value for possibly undefined key

Loris Bennett loris.bennett at fu-berlin.de
Tue Nov 28 08:58:26 EST 2023


duncan smith <duncan at invalid.invalid> writes:

> On 24/11/2023 16:35, duncan smith wrote:
>> On 24/11/2023 14:31, Loris Bennett wrote:
>>> Hi,
>>>
>>> I want to print some records from a database table where one of the
>>> fields contains a JSON string which is read into a dict.  I am doing
>>> something like
>>>
>>>    print(f"{id} {d['foo']} {d['bar']}")
>>>
>>> However, the dict does not always have the same keys, so d['foo'] or
>>> d['bar'] may be undefined.  I can obviously do something like
>>>
>>>    if not 'foo' in d:
>>>      d['foo']="NULL"
>>>    if not 'bar' in d:
>>>      d['bar']="NULL"
>>>    print(f"{id} {d['foo']} {d['bar']}")
>>>
>>> Is there any more compact way of achieving the same thing?
>>>
>>> Cheers,
>>>
>>> Loris
>>>
>> Yes. e.g.
>> d.get('foo', "NULL")
>> Duncan
>
> Or make d a defaultdict.
>
> from collections import defaultdict
>
> dic = defaultdict(lambda:'NULL')
> dic['foo'] = 'astring'
> dic['foo']
> 'astring'
> dic['bar']
> 'NULL'
>
> Duncan
>

I have gone with the 'd.get' solution, as I am just need to print the
dict to the terminal.  The dict is actually from a list of dicts which
is generated by querying a database, so I don't think the defaultdict
approach would be so appropriate, but it's good to know about it.

Thanks,

Loris
-- 
This signature is currently under constuction.


More information about the Python-list mailing list