Python Forum

Full Version: Simple python code error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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'
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.
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.
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
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'
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.