Python 使用多个字典组织数据

发布于 2024-08-11 03:00:18 字数 655 浏览 4 评论 0 原文

我正在尝试创建一个小型服务器类型应用程序,并且有一个关于使用字典组织数据的问题。现在我正在使用连接套接字对数据进行分组(主要是为了验证数据来自何处以及将数据发送回)。像这样的:connected[socket] = account_data。基本上,每个关联的人都会有帐户数据。由于某些字段将大量用于比较和检查信息,例如帐户 ID,因此我想使用另一个字典来加快速度。

例如:要使用上述方法查找 accountID,我必须使用 for 循环来遍历连接中的所有可用连接,查看每个连接的 account_data 中的 accountID,然后进行比较。这似乎是一个缓慢的方法。如果我可以创建一个字典并使用 accountID 作为密钥,我认为它可以加快速度。问题是,我计划使用 3 个不同的字典,所有字典的顺序都不同。有些数据可能会频繁变化,一旦信息发生变化,更新每一个字典似乎比较麻烦;有什么办法可以将它们联系在一起吗?

也许尝试解释我所问问题的一种更简单的方法是: 您有词典 A、词典 B、词典 C 和数据。字典 A、B 和 C 都包含相同的数据。我希望如果数据发生变化,字典 A、B 和 C 中的数据都会发生变化。我当然可以总是执行 dict A = data、dict B = data 等,但一段时间后会在代码中重复。我知道数据是在创建字典后设置的,所以我不确定是否有解决方案。我只是在寻求有关在这种情况下组织数据的最佳方式的建议。

I am trying to create a small server type application and have a question regarding organizing data with dicts. Right now I am grouping the data using the connection socket (mainly to verify where it's coming from and for sending data back out). Something like this: connected[socket] = account_data. Basically, each connected person will have account data. Since certain fields will be used a lot for comparing and checking information, such as an account ID, I want to speed things up with another dict.

For example: to find an accountID with the above method, I would have to use a for loop to go through all available connections in connected, look at the accountID in account_data for each, and then compare it. This seems to be a slow way to do it. If I could create a dict and use the accountID as the key, I think it could speed things up a little. The problem is, I plan on using 3 different dicts all ordered differently. Some data may change frequently and it seems more of a hassle to update every single dict once information changes; is there anyway to link them together?

Maybe an easier way of trying to explain what I am asking is:
You have Dict A, Dict B, Dict C, and Data. Dict A, B, and C all contain the same Data. I want it so if something changes in Data, the Data in Dict A, B, and C all change. I can of course always do dict A = data, dict B = data, etc but would get repetitive in the code after awhile. I know the data is set once the dict is created so I'm not really sure if there is a solution to this. I am just looking for advice on the best way to organize data in this situation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

生寂 2024-08-18 03:00:18

首先,数据不需要被复制。您可以拥有 3 个字典,每个字典使用不同的键,但具有与其值相同的引用。

这样做您只需要更改值对象一次,这将反映在所有字典中(或者更准确地说,因为字典只存储引用,所以它们将是最新的)。

接下来,您需要确保“引用完整性”,即如果删除特定记录,则需要删除所有 3 个字典中的相应字典条目,并且,如果记录被修改,则具有现在更改的键的字典也需要删除删除记录并在新密钥下重新添加。这可以通过一个包含所有 3 个字典并具有 Add()、Remove() 和(如果适用)Update() 方法的类来完成。

First off, the data, needn't be be replicated. You can well have 3 dictionaries each using a different key, but having the same reference as its value.

Doing so you only need to change the value object once and this will be reflected in all dictionaries (or more precisely since the the dictionaries only store a reference, they'll be up to date).

Next you need to ensure "referencial integrity" i.e. if a particular record is deleted, corresponding dictionary entry needs to be be deleted in all 3 dictionaries, and, if the record gets modified, the dictionaries with a key that is now changed also need to be have the record removed and re-added under the new key. This can be done with a class that holds all 3 dictionaries and has Add(), Remove() and (if applicable) Update() methods.

安静被遗忘 2024-08-18 03:00:18

只需执行以下操作:

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

假设 account_data 是一个具有属性的可变对象,这将引用同一对象作为两个字典中的值,当然具有不同的键。它不一定要在一条语句上,即:

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

同一条语句中的多个赋值只是一种方便;使它按照您想要的方式工作的原因是 Python 普遍通过“对象引用”进行操作(在赋值、参数传递、返回语句等中)。

Just do something like:

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

assuming account_data is a mutable object with attributes, this will reference that same object as a value in both dicts, with different keys of course. It doesn't have to be on one statement, i.e.:

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

the multiple assignments in the same statement are just a convenience; what makes it work the way you want is that Python universally operates by "object reference" (in assignments, argument passing, return statements, and so on).

鸵鸟症 2024-08-18 03:00:18

如果您引用了字典,则对字典的更新将反映到带有引用的所有内容。

客户连接并保留一个套接字,sock。您加载他的帐户并将其粘贴在connections[sock]中。然后,您保留一个帐户 ID 字典(另一种方式),并引用帐户 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

当我们执行 sck.send 时,我们在 update_username 中执行的更改将被自动获取,因为引用完全相同。

If you have references to dictionaries, an update to the dictionary will be reflected to everything with a reference.

A customer connects and retains a socket, sock. You load his account and stick it in connections[sock]. Then you keep a dictionary of account IDs (the other way) with references to the accounts, accounts[account_id]. Let's try that...

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

Since we assigned account to two different places, any change to that dictionary (in either structure) will be reflected in the other. So...

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

The change we execute in update_username will automatically be picked up when we do the sck.send, because the reference is exactly the same.

世态炎凉 2024-08-18 03:00:18

也许 Python 的发布/订阅模块之一可以帮助您?
请参阅此问题

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文