首页 > 解决方案 > 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()

标签: python

解决方案


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.


推荐阅读