2

I'm trying to create a program that makes a dictionary with a simple test txt file:

    first
    second
    third

To do this I wrote the following code:

def createDict():
   with open("test.txt","r") as file:
      index = 0
      list = {}
      for index in range(linecount()//3):#parse 3 lines each loop
         list[next(file)] = [next(file),next(file)]  
   return list;

I want the dictionary to look like

first: [second, third]

but what happens is

third: [first, second]

I managed to get the desired output with this change:

def createDict():
   with open("test.txt","r") as file:
      index = 0
      list = {}
      for index in range(linecount()//3):
         line1 = next(file)
         line2 = next(file)
         line3 = next(file)
         list[line1] = [line2,line3]   
   return list;

Why does the first solution not work?

Jark B
  • 31
  • 3
  • 1
    Note that it's generally a bad idea to name objects using any names used by Python's builtins. In this case, you should probably rename your dictionary `list` to something else. – Brendan A. Sep 18 '19 at 15:07
  • From the duplicate: *In an assignment statement, the right-hand side is always evaluated fully before doing the actual setting of variables*. – Martijn Pieters Sep 18 '19 at 15:18
  • 1
    You really don't need to use a line count here either. `for key in file:` (newline, indent) `try:` (newline, indent) `dictionary[key] = [next(file), next(file)]` (newline, dedent) `except StopIteration: pass` would work just fine. If the file line count is not a multiple of 3, one of the two `next()` calls will raise a `StopIteration` exception. – Martijn Pieters Sep 18 '19 at 15:21
  • In the future, please make a [mre]. In this case the code is poorly organized and doesn't even run, but at least it's clear what you're trying to do. – wjandrea Sep 18 '19 at 15:24

1 Answers1

2

The right-hand side of assignment statements is evaluated first, from left to right:

list[next(file)] = [next(file), next(file)]  
#      3               1            2

You can "visualize" this:

def foo(key):
    print(key)
    return key

d = {}
d[foo(3)] = foo(1), foo(2)

This outputs

1
2
3
DeepSpace
  • 78,697
  • 11
  • 109
  • 154