How to append a dictionary in a Redis cache?












0














I want to append dictionary in a Redis cache.



I haven't any problem with adding a dictionary in Redis but I couldn't append several dictionaries into Redis.





Here's an example:



import redis

cli = redis.Redis('localhost')

list_of_dict = [ # dummy
{
'tags': {'module': 'destructor', 'station': 'SNMP'},
'metric_name': 'destructor',
'value': -8555,
'time': '2018-11-13T15:25:07'
},
{
'tags': {'module': 'voltage', 'station': 'SNMP'},
'metric_name': 'voltage',
'value': 222,
'time': '2018-11-13T15:25:09'
}
]

from pprint import pprint

for ld in list_of_dict:
cli.hmset("pythonDict", ld)
# conn.append(key, val) # Need to key value.

pprint(cli.hgetall("pythonDict"))




In the above snippet code .hmset() writes only the last element/dict of list_of_dict in Redis (override) and .append() need to the key,val.



How can I write/append the two dictionaries of list_of_dict on Redis and retrieve it?










share|improve this question





























    0














    I want to append dictionary in a Redis cache.



    I haven't any problem with adding a dictionary in Redis but I couldn't append several dictionaries into Redis.





    Here's an example:



    import redis

    cli = redis.Redis('localhost')

    list_of_dict = [ # dummy
    {
    'tags': {'module': 'destructor', 'station': 'SNMP'},
    'metric_name': 'destructor',
    'value': -8555,
    'time': '2018-11-13T15:25:07'
    },
    {
    'tags': {'module': 'voltage', 'station': 'SNMP'},
    'metric_name': 'voltage',
    'value': 222,
    'time': '2018-11-13T15:25:09'
    }
    ]

    from pprint import pprint

    for ld in list_of_dict:
    cli.hmset("pythonDict", ld)
    # conn.append(key, val) # Need to key value.

    pprint(cli.hgetall("pythonDict"))




    In the above snippet code .hmset() writes only the last element/dict of list_of_dict in Redis (override) and .append() need to the key,val.



    How can I write/append the two dictionaries of list_of_dict on Redis and retrieve it?










    share|improve this question



























      0












      0








      0







      I want to append dictionary in a Redis cache.



      I haven't any problem with adding a dictionary in Redis but I couldn't append several dictionaries into Redis.





      Here's an example:



      import redis

      cli = redis.Redis('localhost')

      list_of_dict = [ # dummy
      {
      'tags': {'module': 'destructor', 'station': 'SNMP'},
      'metric_name': 'destructor',
      'value': -8555,
      'time': '2018-11-13T15:25:07'
      },
      {
      'tags': {'module': 'voltage', 'station': 'SNMP'},
      'metric_name': 'voltage',
      'value': 222,
      'time': '2018-11-13T15:25:09'
      }
      ]

      from pprint import pprint

      for ld in list_of_dict:
      cli.hmset("pythonDict", ld)
      # conn.append(key, val) # Need to key value.

      pprint(cli.hgetall("pythonDict"))




      In the above snippet code .hmset() writes only the last element/dict of list_of_dict in Redis (override) and .append() need to the key,val.



      How can I write/append the two dictionaries of list_of_dict on Redis and retrieve it?










      share|improve this question















      I want to append dictionary in a Redis cache.



      I haven't any problem with adding a dictionary in Redis but I couldn't append several dictionaries into Redis.





      Here's an example:



      import redis

      cli = redis.Redis('localhost')

      list_of_dict = [ # dummy
      {
      'tags': {'module': 'destructor', 'station': 'SNMP'},
      'metric_name': 'destructor',
      'value': -8555,
      'time': '2018-11-13T15:25:07'
      },
      {
      'tags': {'module': 'voltage', 'station': 'SNMP'},
      'metric_name': 'voltage',
      'value': 222,
      'time': '2018-11-13T15:25:09'
      }
      ]

      from pprint import pprint

      for ld in list_of_dict:
      cli.hmset("pythonDict", ld)
      # conn.append(key, val) # Need to key value.

      pprint(cli.hgetall("pythonDict"))




      In the above snippet code .hmset() writes only the last element/dict of list_of_dict in Redis (override) and .append() need to the key,val.



      How can I write/append the two dictionaries of list_of_dict on Redis and retrieve it?







      python redis






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 14 '18 at 5:58

























      asked Nov 13 '18 at 13:58









      Benyamin Jafari

      2,77732036




      2,77732036
























          2 Answers
          2






          active

          oldest

          votes


















          1














          Set the key and value separately. Write the code in the following way:



          for key,val in list_of_dict:
          cli.hset("pythonDict", key, val)

          pprint(cli.hgetall("pythonDict"))


          If you want to store the array as it is and retrieve the value use json package. Below is a sample:



          import json
          cli.set("pythonDict", json.dumps(list_of_dict))
          pprint(json.loads(cli.get("pythonDict")))





          share|improve this answer























          • I don't want to replace same named keys
            – Benyamin Jafari
            Nov 13 '18 at 14:11










          • Writing values to one key will always overwrite the value. Do you want the whole array to be saved?
            – Subhrajyoti Das
            Nov 13 '18 at 15:13










          • I have updated the answer to show you how to save an array
            – Subhrajyoti Das
            Nov 13 '18 at 15:29



















          1














          The approach you are using might turn suboptimal, as you are retrieving full data, appending to it, and saving it.
          Since your requirement is iteratively appending to an existing list, it is better you use a Redis LIST.



          The storage and retrieval approach would be:




          1. Each element of your list would be a string ( which in turn is the
            JSON representation of your single dictionary element)


          2. Whenever you want to append a dictionary to your existing cache, you
            use an LPUSH command on python's redis client. That would
            append your new dictionaries to existing Redis list.


          3. For data retrieval, you would use LRANGE to retrieve your full
            or partial list of dictionaries. LRANGE has equivalent performance
            to HGETALL.



          Example with redis client (the same set of commands can be used in the python redis client) :



          enter image description here






          share|improve this answer























          • Thanks for the answer, but I encountered with this error: ResponseError: wrong number of arguments for 'lpush' command.
            – Benyamin Jafari
            Nov 14 '18 at 8:38










          • problem solved, I had a mistake in .lpush() argument, I forgaot the name arg.
            – Benyamin Jafari
            Nov 14 '18 at 8:48










          • What is 0, -1 meaning in .lrange(name='pythonDict', start=0, end=-1)?
            – Benyamin Jafari
            Nov 14 '18 at 8:59













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53282674%2fhow-to-append-a-dictionary-in-a-redis-cache%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Set the key and value separately. Write the code in the following way:



          for key,val in list_of_dict:
          cli.hset("pythonDict", key, val)

          pprint(cli.hgetall("pythonDict"))


          If you want to store the array as it is and retrieve the value use json package. Below is a sample:



          import json
          cli.set("pythonDict", json.dumps(list_of_dict))
          pprint(json.loads(cli.get("pythonDict")))





          share|improve this answer























          • I don't want to replace same named keys
            – Benyamin Jafari
            Nov 13 '18 at 14:11










          • Writing values to one key will always overwrite the value. Do you want the whole array to be saved?
            – Subhrajyoti Das
            Nov 13 '18 at 15:13










          • I have updated the answer to show you how to save an array
            – Subhrajyoti Das
            Nov 13 '18 at 15:29
















          1














          Set the key and value separately. Write the code in the following way:



          for key,val in list_of_dict:
          cli.hset("pythonDict", key, val)

          pprint(cli.hgetall("pythonDict"))


          If you want to store the array as it is and retrieve the value use json package. Below is a sample:



          import json
          cli.set("pythonDict", json.dumps(list_of_dict))
          pprint(json.loads(cli.get("pythonDict")))





          share|improve this answer























          • I don't want to replace same named keys
            – Benyamin Jafari
            Nov 13 '18 at 14:11










          • Writing values to one key will always overwrite the value. Do you want the whole array to be saved?
            – Subhrajyoti Das
            Nov 13 '18 at 15:13










          • I have updated the answer to show you how to save an array
            – Subhrajyoti Das
            Nov 13 '18 at 15:29














          1












          1








          1






          Set the key and value separately. Write the code in the following way:



          for key,val in list_of_dict:
          cli.hset("pythonDict", key, val)

          pprint(cli.hgetall("pythonDict"))


          If you want to store the array as it is and retrieve the value use json package. Below is a sample:



          import json
          cli.set("pythonDict", json.dumps(list_of_dict))
          pprint(json.loads(cli.get("pythonDict")))





          share|improve this answer














          Set the key and value separately. Write the code in the following way:



          for key,val in list_of_dict:
          cli.hset("pythonDict", key, val)

          pprint(cli.hgetall("pythonDict"))


          If you want to store the array as it is and retrieve the value use json package. Below is a sample:



          import json
          cli.set("pythonDict", json.dumps(list_of_dict))
          pprint(json.loads(cli.get("pythonDict")))






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 13 '18 at 15:28

























          answered Nov 13 '18 at 14:08









          Subhrajyoti Das

          9461023




          9461023












          • I don't want to replace same named keys
            – Benyamin Jafari
            Nov 13 '18 at 14:11










          • Writing values to one key will always overwrite the value. Do you want the whole array to be saved?
            – Subhrajyoti Das
            Nov 13 '18 at 15:13










          • I have updated the answer to show you how to save an array
            – Subhrajyoti Das
            Nov 13 '18 at 15:29


















          • I don't want to replace same named keys
            – Benyamin Jafari
            Nov 13 '18 at 14:11










          • Writing values to one key will always overwrite the value. Do you want the whole array to be saved?
            – Subhrajyoti Das
            Nov 13 '18 at 15:13










          • I have updated the answer to show you how to save an array
            – Subhrajyoti Das
            Nov 13 '18 at 15:29
















          I don't want to replace same named keys
          – Benyamin Jafari
          Nov 13 '18 at 14:11




          I don't want to replace same named keys
          – Benyamin Jafari
          Nov 13 '18 at 14:11












          Writing values to one key will always overwrite the value. Do you want the whole array to be saved?
          – Subhrajyoti Das
          Nov 13 '18 at 15:13




          Writing values to one key will always overwrite the value. Do you want the whole array to be saved?
          – Subhrajyoti Das
          Nov 13 '18 at 15:13












          I have updated the answer to show you how to save an array
          – Subhrajyoti Das
          Nov 13 '18 at 15:29




          I have updated the answer to show you how to save an array
          – Subhrajyoti Das
          Nov 13 '18 at 15:29













          1














          The approach you are using might turn suboptimal, as you are retrieving full data, appending to it, and saving it.
          Since your requirement is iteratively appending to an existing list, it is better you use a Redis LIST.



          The storage and retrieval approach would be:




          1. Each element of your list would be a string ( which in turn is the
            JSON representation of your single dictionary element)


          2. Whenever you want to append a dictionary to your existing cache, you
            use an LPUSH command on python's redis client. That would
            append your new dictionaries to existing Redis list.


          3. For data retrieval, you would use LRANGE to retrieve your full
            or partial list of dictionaries. LRANGE has equivalent performance
            to HGETALL.



          Example with redis client (the same set of commands can be used in the python redis client) :



          enter image description here






          share|improve this answer























          • Thanks for the answer, but I encountered with this error: ResponseError: wrong number of arguments for 'lpush' command.
            – Benyamin Jafari
            Nov 14 '18 at 8:38










          • problem solved, I had a mistake in .lpush() argument, I forgaot the name arg.
            – Benyamin Jafari
            Nov 14 '18 at 8:48










          • What is 0, -1 meaning in .lrange(name='pythonDict', start=0, end=-1)?
            – Benyamin Jafari
            Nov 14 '18 at 8:59


















          1














          The approach you are using might turn suboptimal, as you are retrieving full data, appending to it, and saving it.
          Since your requirement is iteratively appending to an existing list, it is better you use a Redis LIST.



          The storage and retrieval approach would be:




          1. Each element of your list would be a string ( which in turn is the
            JSON representation of your single dictionary element)


          2. Whenever you want to append a dictionary to your existing cache, you
            use an LPUSH command on python's redis client. That would
            append your new dictionaries to existing Redis list.


          3. For data retrieval, you would use LRANGE to retrieve your full
            or partial list of dictionaries. LRANGE has equivalent performance
            to HGETALL.



          Example with redis client (the same set of commands can be used in the python redis client) :



          enter image description here






          share|improve this answer























          • Thanks for the answer, but I encountered with this error: ResponseError: wrong number of arguments for 'lpush' command.
            – Benyamin Jafari
            Nov 14 '18 at 8:38










          • problem solved, I had a mistake in .lpush() argument, I forgaot the name arg.
            – Benyamin Jafari
            Nov 14 '18 at 8:48










          • What is 0, -1 meaning in .lrange(name='pythonDict', start=0, end=-1)?
            – Benyamin Jafari
            Nov 14 '18 at 8:59
















          1












          1








          1






          The approach you are using might turn suboptimal, as you are retrieving full data, appending to it, and saving it.
          Since your requirement is iteratively appending to an existing list, it is better you use a Redis LIST.



          The storage and retrieval approach would be:




          1. Each element of your list would be a string ( which in turn is the
            JSON representation of your single dictionary element)


          2. Whenever you want to append a dictionary to your existing cache, you
            use an LPUSH command on python's redis client. That would
            append your new dictionaries to existing Redis list.


          3. For data retrieval, you would use LRANGE to retrieve your full
            or partial list of dictionaries. LRANGE has equivalent performance
            to HGETALL.



          Example with redis client (the same set of commands can be used in the python redis client) :



          enter image description here






          share|improve this answer














          The approach you are using might turn suboptimal, as you are retrieving full data, appending to it, and saving it.
          Since your requirement is iteratively appending to an existing list, it is better you use a Redis LIST.



          The storage and retrieval approach would be:




          1. Each element of your list would be a string ( which in turn is the
            JSON representation of your single dictionary element)


          2. Whenever you want to append a dictionary to your existing cache, you
            use an LPUSH command on python's redis client. That would
            append your new dictionaries to existing Redis list.


          3. For data retrieval, you would use LRANGE to retrieve your full
            or partial list of dictionaries. LRANGE has equivalent performance
            to HGETALL.



          Example with redis client (the same set of commands can be used in the python redis client) :



          enter image description here







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 14 '18 at 8:52









          Benyamin Jafari

          2,77732036




          2,77732036










          answered Nov 14 '18 at 6:53









          DhruvPathak

          28.6k980136




          28.6k980136












          • Thanks for the answer, but I encountered with this error: ResponseError: wrong number of arguments for 'lpush' command.
            – Benyamin Jafari
            Nov 14 '18 at 8:38










          • problem solved, I had a mistake in .lpush() argument, I forgaot the name arg.
            – Benyamin Jafari
            Nov 14 '18 at 8:48










          • What is 0, -1 meaning in .lrange(name='pythonDict', start=0, end=-1)?
            – Benyamin Jafari
            Nov 14 '18 at 8:59




















          • Thanks for the answer, but I encountered with this error: ResponseError: wrong number of arguments for 'lpush' command.
            – Benyamin Jafari
            Nov 14 '18 at 8:38










          • problem solved, I had a mistake in .lpush() argument, I forgaot the name arg.
            – Benyamin Jafari
            Nov 14 '18 at 8:48










          • What is 0, -1 meaning in .lrange(name='pythonDict', start=0, end=-1)?
            – Benyamin Jafari
            Nov 14 '18 at 8:59


















          Thanks for the answer, but I encountered with this error: ResponseError: wrong number of arguments for 'lpush' command.
          – Benyamin Jafari
          Nov 14 '18 at 8:38




          Thanks for the answer, but I encountered with this error: ResponseError: wrong number of arguments for 'lpush' command.
          – Benyamin Jafari
          Nov 14 '18 at 8:38












          problem solved, I had a mistake in .lpush() argument, I forgaot the name arg.
          – Benyamin Jafari
          Nov 14 '18 at 8:48




          problem solved, I had a mistake in .lpush() argument, I forgaot the name arg.
          – Benyamin Jafari
          Nov 14 '18 at 8:48












          What is 0, -1 meaning in .lrange(name='pythonDict', start=0, end=-1)?
          – Benyamin Jafari
          Nov 14 '18 at 8:59






          What is 0, -1 meaning in .lrange(name='pythonDict', start=0, end=-1)?
          – Benyamin Jafari
          Nov 14 '18 at 8:59




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53282674%2fhow-to-append-a-dictionary-in-a-redis-cache%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)