python - 为redis动态命名元组

标签 python redis

我有一个 csv 文件,其中每一行都包含一个人的 ID #,然后是一堆属性。我希望能够为每个人创建一个包含他们所有属性的元组,然后将元组命名为他们 ID # 的一些变体。

然后所有这些元组将被添加到 redis 中的一个集合中进行存储。

我似乎无法弄清楚如何创建一个以人员 ID# 命名的元组。

我知道动态命名变量不是最佳实践,但我宁愿不将所有元组放在列表中或设置为然后放入 redis 集(这是必须的);它看起来效率低下且麻烦。

这是我现在的代码:

with open('personlist.csv','rb') as f:
for line in f:
        row = line.split(',')
        personID = row[0]
        attrb1 = row[1]
        attrb2 = row[2]
        attrb3 = row[3]
        # Need to name tuple here and define as (attrb1, attrb2, attrb3)
        r.lpush('allpersonslist',tuple)

最佳答案

此示例需要额外的代码才能运行。我假设您使用的是 redis API,例如 redis-py。变量 r 是一个打开的 redis 连接。

import pickle

with open('personlist.csv', 'rb') as f:
    for line in f:
        row = line.split(',')
        personID = row[0]
        attrb1 = row[1]
        attrb2 = row[2]
        attrb3 = row[3]
        #put the attributes in a tuple
        tuple = (attrb1, attrb2, attrb3)
        #serialize the tuple before adding it to the set
        r.set("person/%d" %personID,pickle.dumps(tuple,-1))

def getPerson(Id):
    return pickle.loads(r.get("person/%d" %Id))    

您可以调用 getPerson(5) 返回与 ID 为 5 的人关联的元组。

关于python - 为redis动态命名元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22029711/

相关文章:

python - Windows 文件方案 URI 上的 urlparse() 在开始时留下额外的斜杠

python - 凯拉斯错误 : "BatchNormalization Shape must be rank 1 but is rank 4 for batch_normalization"

python - 在 Pandas 中将列表转换为日期时间

mysql - 将持久对象委托(delegate)给 Redis,使用 MySQL 回退

google-cloud-platform - 无法使用无服务器 VPC 访问设置 Google Cloud Memorystore redis 实例

redis - 一个redis del 命令可以删除多少个key?

node.js - 无法连接到远程 redis 主机 [nodeJS]

python - 在python中有一个列表,使用lambda和map/filter生成新列表

redis - 一个队列实例同步多个Redis实例

python - 从 LineStringField 中提取坐标