Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple python code error
#1
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'
Reply
#2
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.
Reply
#3
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.
Reply
#4
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
Reply
#5
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'
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with simple code JacobSkinner 1 225 Mar-18-2024, 08:08 PM
Last Post: deanhystad
  I have a code which is very simple but still I cannot detect what's wrong with it max22 1 439 Nov-07-2023, 04:32 PM
Last Post: snippsat
  Code error from Fundamentals of Python Programming van Richard L. Halterman Heidi 12 1,600 Jul-25-2023, 10:32 PM
Last Post: Skaperen
  Syntax error while executing the Python code in Linux DivAsh 8 1,450 Jul-19-2023, 06:27 PM
Last Post: Lahearle
  Compiles Python code with no error but giving out no output - what's wrong with it? pythonflea 6 1,468 Mar-27-2023, 07:38 AM
Last Post: buran
  help me simple code result min and max number abrahimusmaximus 2 869 Nov-12-2022, 07:52 AM
Last Post: buran
  Error in if-then-else python code Led_Zeppelin 6 2,283 Jul-27-2022, 07:53 PM
Last Post: deanhystad
  Simple encoding code ebolisa 3 1,399 Jun-18-2022, 10:59 AM
Last Post: deanhystad
  How would you (as an python expert) make this code more efficient/simple coder_sw99 3 1,749 Feb-21-2022, 10:52 AM
Last Post: Gribouillis
  Simple code question about lambda and tuples JasPyt 7 3,236 Oct-04-2021, 05:18 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020