Python value assigned to incorrect dict key

Viewed 44

I am iterating through a csv and for each column, determining the longest len of a string, and updating a dict as necessary.

If I do this

def get_max_size(current, cell_value):
  if cell_value:
    current = max(current, len(cell_value))
  return current

def my_function():

  headers = ["val1","val2","val3","val4","val5"]

  d = {header: {'max_size': 0, 'other': {'test': None}} for header in headers}

  csv_file = [
    ["abc","123","HAMILTON","1950.00","17-SEP-2015"],
    ["ab","321","GLASGOW","711.00","13-NOV-2015"]
  ]

  for row in csv_file:
    for i, header in enumerate(headers):
      max_size = get_max_size(d[header]['max_size'], row[i])
      d[header]['max_size'] = max_size
  print(d)

I get the expected output:

{'val1': {'max_size': 3, 'other': {'test': None}},
  'val2': {'max_size': 3, 'other': {'test': None}},
  'val3': {'max_size': 8, 'other': {'test': None}},
  'val4': {'max_size': 7, 'other': {'test': None}},
  'val5': {'max_size': 11, 'other': {'test': None}}}

However if I modify my code as such:

REQUIRED_VALUES = {
  'max_size': 0,
  'allowed_values': {'digit': None, 'alpha': None, 'whitespace': None, 'symbol': None},
  'max_value': None,
  'allow_null': None,
}

def my_function():

  headers = ["val1","val2","val3","val4","val5"]

  # d = {header: {'max_size': 0, 'other': {'test': None}} for header in headers}
  d = {header: REQUIRED_VALUES for header in headers}

  csv_file = [
    ["abc","123","HAMILTON","1950.00","17-SEP-2015"],
    ["ab","321","GLASGOW","711.00","13-NOV-2015"]
  ]

  for row in csv_file:
    for i, header in enumerate(headers):
      max_size = get_max_size(d[header]['max_size'], row[i])
      d[header]['max_size'] = max_size
  print(d)

Then the largest len of all keys (val5, the date field, of len == 11), is assigned to all max_length:

{'val1': {'max_size': 11, 'allowed_values': {'digit': None, 'alpha': None, 'whitespace': None, 'symbol': None}, 'max_value': None, 'allow_null': None},
  'val2': {'max_size': 11, 'allowed_values': {'digit': None, 'alpha': None, 'whitespace': None, 'symbol': None}, 'max_value': None, 'allow_null': None},
  'val3': {'max_size': 11, 'allowed_values': {'digit': None, 'alpha': None, 'whitespace': None, 'symbol': None}, 'max_value': None, 'allow_null': None},
  'val4': {'max_size': 11, 'allowed_values': {'digit': None, 'alpha': None, 'whitespace': None, 'symbol': None}, 'max_value': None, 'allow_null': None},
  'val5': {'max_size': 11, 'allowed_values': {'digit': None, 'alpha': None, 'whitespace': None, 'symbol': None}, 'max_value': None, 'allow_null': None}}

Is there some difference between the dicts that I'm missing? The dict is the only thing that changes, they both contain nested dictionaries... apart from number of items, I can't really see the difference.

0 Answers
Related