Python Forum
Simple python code error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Simple python code error (/thread-24937.html)



Simple python code error - cls0724 - Mar-11-2020

Hi all,

I am trying to get myself familiar with zip function and turns out Key error 1 keeps popping up when i typed the following program.

I seriously have no idea what's wrong in this program...

a = {}
b = 'hello'
data = '1','2','3'
date = '24','25','26'
for c, d in zip(data, date):
    a[c][d] = [b]
Error:
Traceback (most recent call last): File "/Users/Larry/Documents/Complicated Name List Testing.py", line 26, in <module> a[c][d] = [b] KeyError: '1'



RE: Simple python code error - jefsummers - Mar-11-2020

a is a dictionary. a[c][d] is not how you access a dictionary. Also, not sure why you have b in [] in that line.


RE: Simple python code error - stullis - Mar-11-2020

Interesting. I thought it would raise a NoneType error instead. As I understand it, adding the second index requires an object to work. So, the interpreter is raising the KeyError because the key doesn't exist and so cannot have a value.

To make this work, you'll need to set the values to dicts before setting the those values.


RE: Simple python code error - cls0724 - Mar-12-2020

but why the following codes work by adding another list into the end of the tuple pair?

def init(data):
  data['first'] = {}
  data['middle'] = {}
  data['last'] = {}

def store(data, full_name):
  names = full_name.split()
  if len(names) == 2:name.insert(1, '')
  labels = 'first', 'middle', 'last'
  for label, name in zip(labels, names):
    people = lookup(data, label, name)
    if people:
      people.append(full_name)
    else:
      data[label][name]= [full_name]

def lookup(data, label, name):
  return data[label].get(name)
As you can see above, the else part add [full_name] into each pair of [label][name].
but my a[c][d] = [b] can't work?

Many thanks


RE: Simple python code error - DeaD_EyE - Mar-12-2020

from collections import defaultdict


my_storage = defaultdict(dict)
my_storage["foo"]["bar"] = 42
print(my_storage)
Output:
defaultdict(<class 'dict'>, {'foo': {'bar': 42}})
Not existing keys are automatically created, if you assign accessing them.
But this goes only one level deep.

This won't work:
my_storage["foo"]["bar"]["foo"] = 42
Error:
KeyError: 'bar'



RE: Simple python code error - stullis - Mar-12-2020

In your code, the __init__() method creates the data dict:

def init(data):
  data['first'] = {}
  data['middle'] = {}
  data['last'] = {}
So, the keys are already set. When adding names to the second level dicts, the interpreter retrieves the empty dicts from the first level. In the original code, the interpreter cannot find those empty dicts because they do not exist.