python-3.xlistpython-memcachedpylibmc

Python pylibmc syntax / how can I use mc.set in a loop


I want to set keys in a for loop, and read them back in another script also using a loop. To test memcache is working I made these simple scripts:

a.py

import pylibmc
mc = pylibmc.Client(["127.0.0.1"], binary=True,
        behaviors={"tcp_nodelay": True,
        "ketama": True})
mc["key_1"] = "Value 1"
mc["key_2"] = "Value 2"
mc["key_3"] = "Value 3"
mc["key_4"] = "Value 4"

b.py:

import pylibmc
mc = pylibmc.Client(["127.0.0.1"], binary=True,
        behaviors={"tcp_nodelay": True,
        "ketama": True})
print("%s" % (mc["key_1"]))
print("%s" % (mc["key_2"]))
print("%s" % (mc["key_3"]))
print("%s" % (mc["key_4"]))

This working fine. But I have no clue how to rewrite memcache line to be used in a for loop. I tried several things, but nothing I tried did work. What I want is something like this:

for index in range (0,4):
   mc["key_(index)"] = "Value (index)"

Solution

  • you can use f-strings:

    for index in range (0,4):
        key = f"key_{index}"
        mc[key] = f"{mc[key]} {index}" # or "Value {index}"