Python organizes data with multiple dictionaries

I am trying to create a small server-type application and ask a question about organizing data using dicts. Right now I am grouping data using a connection socket (mainly to check where it comes from and to send data). Something like this: connected[socket] = account_data. In principle, each connected person will have account information. Since some fields will be used to compare and verify information, such as account ID, I want to speed up work with another dict.

For example: to find the account ID with the above method, I would have to use the for loop to go through all the available connections in the connection, look at the account ID in account_data for each, and then compare it. This seems to be a slow way to do this. If I could create a dict and use the accountID as the key, I think this might speed things up a bit. The problem is that I plan to use 3 different dicts, all ordered in different ways. Some data can change frequently, and it seems more hassle to update each individual dict after changing the information; is there anyway to tie them together?

Maybe an easier way to explain what I ask: You have Dict A, Dict B, Dict C and Data. Dict A, B and C contain the same data. I want this to happen if something changes in Data, the data in Dict A, B and C all change. Of course, I can always do dict A = data, dict B = data, etc., but after a while they will be repeated in the code. I know that data is set after creating a dict, so I'm not sure if there is a solution for this. I'm just looking for advice on the best way to organize data in this situation.

+3
source share
4 answers

If you have links to dictionaries, a dictionary update will be reflected in everything with a link.

, sock. connections[sock]. ( ) , accounts[account_id]. ...

connected = {}
accounts = {}

def load_account(acct):
    return db_magic(acct)                             # Grab a dictionary from the DB

def somebody_connected(sck, acct):
    global connected, accounts
    account = load_account(acct)
    connected[sck] = account                          # Now we have it by socket
    accounts[acct["accountid"]] = account             # Now we have it by account ID

account , ( ) . ...

def update_username(acct_id, new_username):
    accounts[acct_id]["username"] = new_username

def what_is_my_username(sck):
    sck.send(connected[sck]["username"])              # In response to GIMME_USERNAME

, update_username, , sck.send, .

0

-, . 3 , , , .

, (, , ).

" ", , , 3 , , , , . , 3 Add(), Remove() ( ) Update().

+2

- :

connected[socket] = accountids[account_data.accountid] = account_data

, account_data , , dicts, , . , :

connected[socket] = account_data
accountids[account_data.accountid] = account_data

- ; , , , Python " " ( , , ..).

+1
source

Maybe one of the Python publish / subscribe modules can help you here? See this question .

0
source

Source: https://habr.com/ru/post/1722649/


All Articles