nested dictionary with list of tuples as values from DATA file in python









up vote
1
down vote

favorite












Please, help. I have a data file with 4 columns (userid, movieid, score, timestamp) that looks like this:



196 242 3 881250949
186 302 3 891717742
22 377 1 878887116
196 51 2 880606923
62 257 2 879372434


I am trying to create a nested dictionary that should look like this:




users = '196': [('242', '3'), ('51', '2')], '186': ['302','3'] ...




My code only picks up one tuple (movieid, score) for each userid:



def create_users_dict():
try:
users =
for line in open('u.data'):
(id, movieid, rating, timestamp) = line.split('t')[0:4]
users[id] = (movieid, rating)
except IOError as ioerr:
print('There is an error with the file:' + str(ioerr))
return users
users = create_users_dict()



users = '196': ('51', '2'), '186': ('302', '3')...











share|improve this question



























    up vote
    1
    down vote

    favorite












    Please, help. I have a data file with 4 columns (userid, movieid, score, timestamp) that looks like this:



    196 242 3 881250949
    186 302 3 891717742
    22 377 1 878887116
    196 51 2 880606923
    62 257 2 879372434


    I am trying to create a nested dictionary that should look like this:




    users = '196': [('242', '3'), ('51', '2')], '186': ['302','3'] ...




    My code only picks up one tuple (movieid, score) for each userid:



    def create_users_dict():
    try:
    users =
    for line in open('u.data'):
    (id, movieid, rating, timestamp) = line.split('t')[0:4]
    users[id] = (movieid, rating)
    except IOError as ioerr:
    print('There is an error with the file:' + str(ioerr))
    return users
    users = create_users_dict()



    users = '196': ('51', '2'), '186': ('302', '3')...











    share|improve this question

























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      Please, help. I have a data file with 4 columns (userid, movieid, score, timestamp) that looks like this:



      196 242 3 881250949
      186 302 3 891717742
      22 377 1 878887116
      196 51 2 880606923
      62 257 2 879372434


      I am trying to create a nested dictionary that should look like this:




      users = '196': [('242', '3'), ('51', '2')], '186': ['302','3'] ...




      My code only picks up one tuple (movieid, score) for each userid:



      def create_users_dict():
      try:
      users =
      for line in open('u.data'):
      (id, movieid, rating, timestamp) = line.split('t')[0:4]
      users[id] = (movieid, rating)
      except IOError as ioerr:
      print('There is an error with the file:' + str(ioerr))
      return users
      users = create_users_dict()



      users = '196': ('51', '2'), '186': ('302', '3')...











      share|improve this question















      Please, help. I have a data file with 4 columns (userid, movieid, score, timestamp) that looks like this:



      196 242 3 881250949
      186 302 3 891717742
      22 377 1 878887116
      196 51 2 880606923
      62 257 2 879372434


      I am trying to create a nested dictionary that should look like this:




      users = '196': [('242', '3'), ('51', '2')], '186': ['302','3'] ...




      My code only picks up one tuple (movieid, score) for each userid:



      def create_users_dict():
      try:
      users =
      for line in open('u.data'):
      (id, movieid, rating, timestamp) = line.split('t')[0:4]
      users[id] = (movieid, rating)
      except IOError as ioerr:
      print('There is an error with the file:' + str(ioerr))
      return users
      users = create_users_dict()



      users = '196': ('51', '2'), '186': ('302', '3')...








      python






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 10 at 17:36









      Daniel Mesejo

      7,9841922




      7,9841922










      asked Nov 10 at 17:24









      LMHull

      426




      426






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          Use setdefault:



          def create_users_dict():
          try:
          users =
          for line in open('u.data'):
          uid, movie_id, rating, timestamp = line.split()
          users.setdefault(uid, ).append((movie_id, rating))
          return users
          except IOError as ioerr:
          print('There is an error with the file:' + str(ioerr))
          users = create_users_dict()

          print(users)


          Output



          '196': [('242', '3'), ('51', '2')], '62': [('257', '2')], '186': [('302', '3')], '22': [('377', '1')]


          A possible alternative is to check if the key (uid) is in the dictionary, in case is missing initialize the value with the empty list and then simply append.



          def create_users_dict():
          try:
          users =
          for line in open('u.dat'):
          uid, movie_id, rating, timestamp = line.split()
          if uid not in users:
          users[uid] =
          users[uid].append((movie_id, rating))
          return users
          except IOError as ioerr:
          print('There is an error with the file:' + str(ioerr))


          As a side note you should not use id as a name because it shadows the built-in function id.






          share|improve this answer






















          • Fantastic! Very much thank you!!!
            – LMHull
            Nov 10 at 18:41










          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',
          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%2f53241535%2fnested-dictionary-with-list-of-tuples-as-values-from-data-file-in-python%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          Use setdefault:



          def create_users_dict():
          try:
          users =
          for line in open('u.data'):
          uid, movie_id, rating, timestamp = line.split()
          users.setdefault(uid, ).append((movie_id, rating))
          return users
          except IOError as ioerr:
          print('There is an error with the file:' + str(ioerr))
          users = create_users_dict()

          print(users)


          Output



          '196': [('242', '3'), ('51', '2')], '62': [('257', '2')], '186': [('302', '3')], '22': [('377', '1')]


          A possible alternative is to check if the key (uid) is in the dictionary, in case is missing initialize the value with the empty list and then simply append.



          def create_users_dict():
          try:
          users =
          for line in open('u.dat'):
          uid, movie_id, rating, timestamp = line.split()
          if uid not in users:
          users[uid] =
          users[uid].append((movie_id, rating))
          return users
          except IOError as ioerr:
          print('There is an error with the file:' + str(ioerr))


          As a side note you should not use id as a name because it shadows the built-in function id.






          share|improve this answer






















          • Fantastic! Very much thank you!!!
            – LMHull
            Nov 10 at 18:41














          up vote
          1
          down vote



          accepted










          Use setdefault:



          def create_users_dict():
          try:
          users =
          for line in open('u.data'):
          uid, movie_id, rating, timestamp = line.split()
          users.setdefault(uid, ).append((movie_id, rating))
          return users
          except IOError as ioerr:
          print('There is an error with the file:' + str(ioerr))
          users = create_users_dict()

          print(users)


          Output



          '196': [('242', '3'), ('51', '2')], '62': [('257', '2')], '186': [('302', '3')], '22': [('377', '1')]


          A possible alternative is to check if the key (uid) is in the dictionary, in case is missing initialize the value with the empty list and then simply append.



          def create_users_dict():
          try:
          users =
          for line in open('u.dat'):
          uid, movie_id, rating, timestamp = line.split()
          if uid not in users:
          users[uid] =
          users[uid].append((movie_id, rating))
          return users
          except IOError as ioerr:
          print('There is an error with the file:' + str(ioerr))


          As a side note you should not use id as a name because it shadows the built-in function id.






          share|improve this answer






















          • Fantastic! Very much thank you!!!
            – LMHull
            Nov 10 at 18:41












          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          Use setdefault:



          def create_users_dict():
          try:
          users =
          for line in open('u.data'):
          uid, movie_id, rating, timestamp = line.split()
          users.setdefault(uid, ).append((movie_id, rating))
          return users
          except IOError as ioerr:
          print('There is an error with the file:' + str(ioerr))
          users = create_users_dict()

          print(users)


          Output



          '196': [('242', '3'), ('51', '2')], '62': [('257', '2')], '186': [('302', '3')], '22': [('377', '1')]


          A possible alternative is to check if the key (uid) is in the dictionary, in case is missing initialize the value with the empty list and then simply append.



          def create_users_dict():
          try:
          users =
          for line in open('u.dat'):
          uid, movie_id, rating, timestamp = line.split()
          if uid not in users:
          users[uid] =
          users[uid].append((movie_id, rating))
          return users
          except IOError as ioerr:
          print('There is an error with the file:' + str(ioerr))


          As a side note you should not use id as a name because it shadows the built-in function id.






          share|improve this answer














          Use setdefault:



          def create_users_dict():
          try:
          users =
          for line in open('u.data'):
          uid, movie_id, rating, timestamp = line.split()
          users.setdefault(uid, ).append((movie_id, rating))
          return users
          except IOError as ioerr:
          print('There is an error with the file:' + str(ioerr))
          users = create_users_dict()

          print(users)


          Output



          '196': [('242', '3'), ('51', '2')], '62': [('257', '2')], '186': [('302', '3')], '22': [('377', '1')]


          A possible alternative is to check if the key (uid) is in the dictionary, in case is missing initialize the value with the empty list and then simply append.



          def create_users_dict():
          try:
          users =
          for line in open('u.dat'):
          uid, movie_id, rating, timestamp = line.split()
          if uid not in users:
          users[uid] =
          users[uid].append((movie_id, rating))
          return users
          except IOError as ioerr:
          print('There is an error with the file:' + str(ioerr))


          As a side note you should not use id as a name because it shadows the built-in function id.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 10 at 17:39

























          answered Nov 10 at 17:34









          Daniel Mesejo

          7,9841922




          7,9841922











          • Fantastic! Very much thank you!!!
            – LMHull
            Nov 10 at 18:41
















          • Fantastic! Very much thank you!!!
            – LMHull
            Nov 10 at 18:41















          Fantastic! Very much thank you!!!
          – LMHull
          Nov 10 at 18:41




          Fantastic! Very much thank you!!!
          – LMHull
          Nov 10 at 18:41

















           

          draft saved


          draft discarded















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53241535%2fnested-dictionary-with-list-of-tuples-as-values-from-data-file-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







          這個網誌中的熱門文章

          What does pagestruct do in Eviews?

          Dutch intervention in Lombok and Karangasem

          Channel Islands