sending data to two list items in python



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















Python Script:



msg = """
Device: Main1
ID: 1111
status: OK

Device: Main1
ID: 2222
Status: OK

Device: Main2
ID: 3333
status: OK

Device: Main2
ID: 4444
Status: OK
"""
main1_id =
main2_id =

for line in msg.split("n"):
if line.startswith("ID:"):
main1_id.append(line)
print main1_id
print main2_id


I have msg variable data. I want to add id's of this data to two different lists main1_id and main2_id if the Device is Main1 and Main2 respectively.
I tried to implement this in above code. I stuck and I need help.



output:



['ID: 1111', 'ID: 2222', 'ID: 3333', 'ID: 4444']



Expected output:



['ID: 1111', 'ID: 2222']
['ID: 3333', 'ID: 4444']









share|improve this question



















  • 2





    You never append something to main2_id. Why do you expect that it contains some items?

    – mkrieger1
    Nov 15 '18 at 15:27











  • Do you just need the id's?

    – Kedar Kodgire
    Nov 15 '18 at 15:29











  • Just trying to explain requirement ..i posted question like this

    – sagar_dev
    Nov 15 '18 at 15:30











  • @Kedar, yes only ID's

    – sagar_dev
    Nov 15 '18 at 15:31

















0















Python Script:



msg = """
Device: Main1
ID: 1111
status: OK

Device: Main1
ID: 2222
Status: OK

Device: Main2
ID: 3333
status: OK

Device: Main2
ID: 4444
Status: OK
"""
main1_id =
main2_id =

for line in msg.split("n"):
if line.startswith("ID:"):
main1_id.append(line)
print main1_id
print main2_id


I have msg variable data. I want to add id's of this data to two different lists main1_id and main2_id if the Device is Main1 and Main2 respectively.
I tried to implement this in above code. I stuck and I need help.



output:



['ID: 1111', 'ID: 2222', 'ID: 3333', 'ID: 4444']



Expected output:



['ID: 1111', 'ID: 2222']
['ID: 3333', 'ID: 4444']









share|improve this question



















  • 2





    You never append something to main2_id. Why do you expect that it contains some items?

    – mkrieger1
    Nov 15 '18 at 15:27











  • Do you just need the id's?

    – Kedar Kodgire
    Nov 15 '18 at 15:29











  • Just trying to explain requirement ..i posted question like this

    – sagar_dev
    Nov 15 '18 at 15:30











  • @Kedar, yes only ID's

    – sagar_dev
    Nov 15 '18 at 15:31













0












0








0








Python Script:



msg = """
Device: Main1
ID: 1111
status: OK

Device: Main1
ID: 2222
Status: OK

Device: Main2
ID: 3333
status: OK

Device: Main2
ID: 4444
Status: OK
"""
main1_id =
main2_id =

for line in msg.split("n"):
if line.startswith("ID:"):
main1_id.append(line)
print main1_id
print main2_id


I have msg variable data. I want to add id's of this data to two different lists main1_id and main2_id if the Device is Main1 and Main2 respectively.
I tried to implement this in above code. I stuck and I need help.



output:



['ID: 1111', 'ID: 2222', 'ID: 3333', 'ID: 4444']



Expected output:



['ID: 1111', 'ID: 2222']
['ID: 3333', 'ID: 4444']









share|improve this question
















Python Script:



msg = """
Device: Main1
ID: 1111
status: OK

Device: Main1
ID: 2222
Status: OK

Device: Main2
ID: 3333
status: OK

Device: Main2
ID: 4444
Status: OK
"""
main1_id =
main2_id =

for line in msg.split("n"):
if line.startswith("ID:"):
main1_id.append(line)
print main1_id
print main2_id


I have msg variable data. I want to add id's of this data to two different lists main1_id and main2_id if the Device is Main1 and Main2 respectively.
I tried to implement this in above code. I stuck and I need help.



output:



['ID: 1111', 'ID: 2222', 'ID: 3333', 'ID: 4444']



Expected output:



['ID: 1111', 'ID: 2222']
['ID: 3333', 'ID: 4444']






python string python-2.7 dictionary defaultdict






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 16:31









jpp

103k2167117




103k2167117










asked Nov 15 '18 at 15:25









sagar_devsagar_dev

416




416







  • 2





    You never append something to main2_id. Why do you expect that it contains some items?

    – mkrieger1
    Nov 15 '18 at 15:27











  • Do you just need the id's?

    – Kedar Kodgire
    Nov 15 '18 at 15:29











  • Just trying to explain requirement ..i posted question like this

    – sagar_dev
    Nov 15 '18 at 15:30











  • @Kedar, yes only ID's

    – sagar_dev
    Nov 15 '18 at 15:31












  • 2





    You never append something to main2_id. Why do you expect that it contains some items?

    – mkrieger1
    Nov 15 '18 at 15:27











  • Do you just need the id's?

    – Kedar Kodgire
    Nov 15 '18 at 15:29











  • Just trying to explain requirement ..i posted question like this

    – sagar_dev
    Nov 15 '18 at 15:30











  • @Kedar, yes only ID's

    – sagar_dev
    Nov 15 '18 at 15:31







2




2





You never append something to main2_id. Why do you expect that it contains some items?

– mkrieger1
Nov 15 '18 at 15:27





You never append something to main2_id. Why do you expect that it contains some items?

– mkrieger1
Nov 15 '18 at 15:27













Do you just need the id's?

– Kedar Kodgire
Nov 15 '18 at 15:29





Do you just need the id's?

– Kedar Kodgire
Nov 15 '18 at 15:29













Just trying to explain requirement ..i posted question like this

– sagar_dev
Nov 15 '18 at 15:30





Just trying to explain requirement ..i posted question like this

– sagar_dev
Nov 15 '18 at 15:30













@Kedar, yes only ID's

– sagar_dev
Nov 15 '18 at 15:31





@Kedar, yes only ID's

– sagar_dev
Nov 15 '18 at 15:31












2 Answers
2






active

oldest

votes


















0














Use a dictionary



You should try to avoid creating a variable number of variables in this way. Here you can use collections.defaultdict:



from collections import defaultdict

dd = defaultdict(list)
L = msg.split('n')

for idx, line in enumerate(L):
if line.startswith('Device'):
dd[line.split(': ')[-1]].append(int(L[idx+1].split(': ')[-1]))


Result:



defaultdict(list, 'Main1': [1111, 2222],
'Main2': [3333, 4444])


Then access your lists via dd['Main1'] and dd['Main2'].






share|improve this answer






























    0














    You probably want a defualtdict and a basic syntax parser to handle this. Id go with something along the lines of this using regex and collections to save myself time. This code will also emit Error if the file syntax is bad which is a good thing.



    import collections 
    ids = collections.defualtdict(list)
    line_regex = r"(w*): *(w*)"

    for line in input.split():

    if not line.strip():
    continue

    key, value = re.match(line_regex, line).groups()
    if key == 'Device':
    cur_device = value
    if key == 'ID' and cur_device is not None:
    ids[cur_device].append(value)
    cur_device = None
    if key == 'ID' and cur_device is None:
    raise SyntaxError('Could not parse input')





    share|improve this answer

























      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%2f53322678%2fsending-data-to-two-list-items-in-python%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









      0














      Use a dictionary



      You should try to avoid creating a variable number of variables in this way. Here you can use collections.defaultdict:



      from collections import defaultdict

      dd = defaultdict(list)
      L = msg.split('n')

      for idx, line in enumerate(L):
      if line.startswith('Device'):
      dd[line.split(': ')[-1]].append(int(L[idx+1].split(': ')[-1]))


      Result:



      defaultdict(list, 'Main1': [1111, 2222],
      'Main2': [3333, 4444])


      Then access your lists via dd['Main1'] and dd['Main2'].






      share|improve this answer



























        0














        Use a dictionary



        You should try to avoid creating a variable number of variables in this way. Here you can use collections.defaultdict:



        from collections import defaultdict

        dd = defaultdict(list)
        L = msg.split('n')

        for idx, line in enumerate(L):
        if line.startswith('Device'):
        dd[line.split(': ')[-1]].append(int(L[idx+1].split(': ')[-1]))


        Result:



        defaultdict(list, 'Main1': [1111, 2222],
        'Main2': [3333, 4444])


        Then access your lists via dd['Main1'] and dd['Main2'].






        share|improve this answer

























          0












          0








          0







          Use a dictionary



          You should try to avoid creating a variable number of variables in this way. Here you can use collections.defaultdict:



          from collections import defaultdict

          dd = defaultdict(list)
          L = msg.split('n')

          for idx, line in enumerate(L):
          if line.startswith('Device'):
          dd[line.split(': ')[-1]].append(int(L[idx+1].split(': ')[-1]))


          Result:



          defaultdict(list, 'Main1': [1111, 2222],
          'Main2': [3333, 4444])


          Then access your lists via dd['Main1'] and dd['Main2'].






          share|improve this answer













          Use a dictionary



          You should try to avoid creating a variable number of variables in this way. Here you can use collections.defaultdict:



          from collections import defaultdict

          dd = defaultdict(list)
          L = msg.split('n')

          for idx, line in enumerate(L):
          if line.startswith('Device'):
          dd[line.split(': ')[-1]].append(int(L[idx+1].split(': ')[-1]))


          Result:



          defaultdict(list, 'Main1': [1111, 2222],
          'Main2': [3333, 4444])


          Then access your lists via dd['Main1'] and dd['Main2'].







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 15 '18 at 15:36









          jppjpp

          103k2167117




          103k2167117























              0














              You probably want a defualtdict and a basic syntax parser to handle this. Id go with something along the lines of this using regex and collections to save myself time. This code will also emit Error if the file syntax is bad which is a good thing.



              import collections 
              ids = collections.defualtdict(list)
              line_regex = r"(w*): *(w*)"

              for line in input.split():

              if not line.strip():
              continue

              key, value = re.match(line_regex, line).groups()
              if key == 'Device':
              cur_device = value
              if key == 'ID' and cur_device is not None:
              ids[cur_device].append(value)
              cur_device = None
              if key == 'ID' and cur_device is None:
              raise SyntaxError('Could not parse input')





              share|improve this answer





























                0














                You probably want a defualtdict and a basic syntax parser to handle this. Id go with something along the lines of this using regex and collections to save myself time. This code will also emit Error if the file syntax is bad which is a good thing.



                import collections 
                ids = collections.defualtdict(list)
                line_regex = r"(w*): *(w*)"

                for line in input.split():

                if not line.strip():
                continue

                key, value = re.match(line_regex, line).groups()
                if key == 'Device':
                cur_device = value
                if key == 'ID' and cur_device is not None:
                ids[cur_device].append(value)
                cur_device = None
                if key == 'ID' and cur_device is None:
                raise SyntaxError('Could not parse input')





                share|improve this answer



























                  0












                  0








                  0







                  You probably want a defualtdict and a basic syntax parser to handle this. Id go with something along the lines of this using regex and collections to save myself time. This code will also emit Error if the file syntax is bad which is a good thing.



                  import collections 
                  ids = collections.defualtdict(list)
                  line_regex = r"(w*): *(w*)"

                  for line in input.split():

                  if not line.strip():
                  continue

                  key, value = re.match(line_regex, line).groups()
                  if key == 'Device':
                  cur_device = value
                  if key == 'ID' and cur_device is not None:
                  ids[cur_device].append(value)
                  cur_device = None
                  if key == 'ID' and cur_device is None:
                  raise SyntaxError('Could not parse input')





                  share|improve this answer















                  You probably want a defualtdict and a basic syntax parser to handle this. Id go with something along the lines of this using regex and collections to save myself time. This code will also emit Error if the file syntax is bad which is a good thing.



                  import collections 
                  ids = collections.defualtdict(list)
                  line_regex = r"(w*): *(w*)"

                  for line in input.split():

                  if not line.strip():
                  continue

                  key, value = re.match(line_regex, line).groups()
                  if key == 'Device':
                  cur_device = value
                  if key == 'ID' and cur_device is not None:
                  ids[cur_device].append(value)
                  cur_device = None
                  if key == 'ID' and cur_device is None:
                  raise SyntaxError('Could not parse input')






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 15 '18 at 15:46

























                  answered Nov 15 '18 at 15:40









                  gbtimmongbtimmon

                  3,33011528




                  3,33011528



























                      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.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53322678%2fsending-data-to-two-list-items-in-python%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

                      Kleinkühnau

                      Makov (Slowakei)

                      Deutsches Schauspielhaus