python - Pythonic way to populate a dictionary from list of records
问题描述
Background
I have a module called db.py
that is basically consist of wrapper functions that make calls to the db. I have a table called nba and that has columns like player_name
age
player_id
etc.
I have a simple function called db_cache()
where i make a call to the db table and request to get all the player ids. The output of the response
looks something like this
[Record(player_id='31200952409069'), Record(player_id='31201050710077'), Record(player_id='31201050500545'), Record(player_id='31001811412442'), Record(player_id='31201050607711')]
Then I simply iterate through the list and dump each item inside a dictionary.
I am wondering if there is a more pythonic way to populate the dictionary?
My code
def db_cache():
my_dict: Dict[str, None] = {}
response = db.run_query(sql="SELECT player_id FROM nba")
for item in response:
my_dict[item.player_id] = None
return my_dict
my_dict = db_cache()
解决方案
This is built-in to the dict
type:
>>> help(dict.fromkeys)
Help on built-in function fromkeys:
fromkeys(iterable, value=None, /) method of builtins.type instance
Create a new dictionary with keys from iterable and values set to value.
The value
we want is the default of None
, so all we need is:
my_dict = dict.from_keys(db.run_query(sql="SELECT player_id FROM nba"))
Note that the value
will be reused, and not copied, which can cause problems if you want to use a mutable value
. In these cases, you should instead simply use the dict comprehension, as given in @AvihayTsayeg's answer.
推荐阅读
- kotlin - 如何在 Kotlin 中只显示小时?显示数据 hh:mm:ss 但我只想显示 hh:mm:ss 到 hh
- javascript - 如何使用 jQuery .html() 传递变量和一些 HTML
- excel - Excel:制作折扣总成本的公式
- node.js - 在 hexo d 之后,当 diaplay 从公用文件夹复制文件时... git 停止了,我不知道为什么
- google-chrome-extension - 如何确保扩展服务工作者的事件处理程序中的异步调用运行完成?
- apple-id - 如何重置 Apple ID 隐私问答?
- dynamics-crm - Microsoft Dynamics CRM 中活动的安全角色
- python-3.x - Python:采用数组输入的函数的多维集成
- sql - 从 SQL 中删除未使用的 CTE
- python - Conda 更新后打开 Spyder 的问题