Printing dict value for possibly undefined key
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 -- This signature is currently under constuction. -- https://mail.python.org/mailman/listinfo/python-list
Re: Printing dict value for possibly undefined key
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 -- https://mail.python.org/mailman/listinfo/python-list
Re: Silly/crazy problem with sqlite
I really can't think of a case where the missing comma would make any sense at all. That is pretty tricky, yes. The comma means it's a tuple. Without the comma, it's just a string with parenthesis around it, which is a string. PyDev console: starting. Python 3.9.15 (main, Oct 28 2022, 17:28:38) [GCC] on linux x = ('%' + "2023-11" + '%') x '%2023-11%' x = ('%' + x + '%',) x ('%%2023-11%%',) x.__class__.__name__ 'tuple' -- https://mail.python.org/mailman/listinfo/python-list
Re: Printing dict value for possibly undefined key
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 -- https://mail.python.org/mailman/listinfo/python-list
Silly/crazy problem with sqlite
This is driving me crazy, I'm running this code:- #!/usr/bin/env python3 # # # Show the electric fence history, default to last 24 hours # import sqlite3 import datetime import sys today = datetime.datetime.now() today = str(today) x = str(today[0:10]) print(x) fdb = sqlite3.connect("/home/chris/.share/newbourne.db") cr = fdb.cursor() sql = "SELECT * FROM fence where datetime LIKE ?" cr.execute(sql, ('%' + "2023-11" + '%')) rv = cr.fetchall() for d in rv: print(d) fdb.commit() fdb.close() Forget about the 'today =' bits, they no longer do anything. When I run the above I get:- chris@esprimo$ fence.py 2023-11-24 Traceback (most recent call last): File "/home/chris/dev/bin/fence.py", line 19, in cr.execute(sql, ('%' + "2023-11" + '%')) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 9 supplied. chris@esprimo$ It's treating the "2023-11" plus % at each end as separate variables to the binding, this is crazy! I've done similar elsewhere and it works OK, what on earth am I doing wrong here? It has to be something very silly but I can't see it at the moment. -- Chris Green · -- https://mail.python.org/mailman/listinfo/python-list
Re: Silly/crazy problem with sqlite
Chris Green wrote: > This is driving me crazy, I'm running this code:- OK, I've found what's wrong:- > cr.execute(sql, ('%' + "2023-11" + '%')) should be:- cr.execute(sql, ('%' + x + '%',) ) I have to say this seems very non-pythonesque to me, the 'obvious' default simply doesn't work right, and I really can't think of a case where the missing comma would make any sense at all. Maybe I've had too much to eat and drink tonight! :-) -- Chris Green · -- https://mail.python.org/mailman/listinfo/python-list
Re: Silly/crazy problem with sqlite
Am 24.11.2023 um 22:49 schrieb Rimu Atkinson via Python-list: I really can't think of a case where the missing comma would make any sense at all. That is pretty tricky, yes. The comma means it's a tuple. Without the comma, it's just a string with parenthesis around it, which is a string. Placeholders for the parameters in an SQL command for sqlite3.execute(..) must always be given as dict or sequence. Even if it's just one parameter. Same thing with other database modules, it's given in PEP 249. HTH Sibylle -- https://mail.python.org/mailman/listinfo/python-list
Re: Silly/crazy problem with sqlite
On 11/24/23 14:10, Chris Green via Python-list wrote: Chris Green wrote: This is driving me crazy, I'm running this code:- OK, I've found what's wrong:- cr.execute(sql, ('%' + "2023-11" + '%')) should be:- cr.execute(sql, ('%' + x + '%',) ) I have to say this seems very non-pythonesque to me, the 'obvious' default simply doesn't work right, and I really can't think of a case where the missing comma would make any sense at all. as noted, the comma makes it a tuple. this might be a case where rewriting as an f-string makes it just a little more readable, since the syntax will make it look like there's a single string followed by a comma - the addition just makes it look less clear to my eyes: cr.execute(sql, (f'%2023-11%', )) cr.execute(sql, (f'%{x}%', )) -- https://mail.python.org/mailman/listinfo/python-list
Re: Printing dict value for possibly undefined key
On 11/25/2023 3:31 AM, Loris Bennett via Python-list 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? What does "the dict does not always have the same keys" mean? a) there are two (or...) keys, but some records don't include both; b) there may be keys other than 'foo' and 'bar' which not-known in-advance; c) something else. As mentioned, dict.get() solves one of these. Otherwise, there are dict methods which collect/reveal all the keys, all the values, or both - dict.keys(), .values(), .items(), resp. -- Regards =dn -- https://mail.python.org/mailman/listinfo/python-list
Re: Silly/crazy problem with sqlite
On 11/24/2023 4:49 PM, Rimu Atkinson via Python-list wrote: I really can't think of a case where the missing comma would make any sense at all. That is pretty tricky, yes. The comma means it's a tuple. Without the comma, it's just a string with parenthesis around it, which is a string. PyDev console: starting. Python 3.9.15 (main, Oct 28 2022, 17:28:38) [GCC] on linux x = ('%' + "2023-11" + '%') x '%2023-11%' x = ('%' + x + '%',) x ('%%2023-11%%',) x.__class__.__name__ 'tuple' To make it very clear in your code so that you are reminded next time you want to re-use it, you could write param = '%2023-11%' cr.execute(sql, (param,)) Probably the param value will actually use a variable instead of the hard-coded value in the example. So use an f-string, because it's more readable and easier to get right: date = ... # Where ever the actual date value comes from param = f'%{date}%' cr.execute(sql, (param,)) -- https://mail.python.org/mailman/listinfo/python-list