简体   繁体   中英

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.

my_arr = [1,2,3,4]
my_dict = {"item":item for item in my_arr}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM