By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,075 Members | 985 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,075 IT Pros & Developers. It's quick & easy.

Weird errors when trying to access a dictionary key

P: n/a
I have a data structure that looks like this:

# dates = {'2007': {'25': {'06/23/07': {'aerosmith': [{'sweet
emotion': 1}, {'dream on': 2}],
# 'Metallica': [{'Fade to
Black': 1}, {'Master of Puppets': 1}]},
# 'last_song': [Master of Puppets', 'Fade to Black',
'sweet emotion']}}}

I have a section where I try to loop through a set of dates and print
out all of the songs for a given artist:

if type == 'artist':
rpt_file.writelines('Song Summary for ' + artist + '\n\n')
for year in sorted(rpt_dates):
for week in sorted(rpt_dates[year]):
for date in sorted(dates[year][week]):
if artist in dates[year][week][date]:
report.append(date)
for song in sorted(dates[year][week][date]
[artist]):
rpt_file.writelines('\t' + [song].keys() \
+ '\t' +
[song].values() + '\n')
I get the following error:

Traceback (most recent call last):
File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 1843, in runMain
self.dbg.runfile(debug_args[0], debug_args)
File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 1538, in runfile
h_execfile(file, args, module=main, tracer=self)
File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 596, in __init__
execfile(file, globals, locals)
File "C:\scripts\python\Songs\song_report.py", line 136, in <module>
if __name__== '__main__': main()
File "C:\scripts\python\Songs\song_report.py", line 134, in main
print_rpt(options.type, rpt_dates, dates, args)
File "C:\scripts\python\Songs\song_report.py", line 107, in
print_rpt
+ '\t' + [song].values() + '\n')
AttributeError: 'list' object has no attribute 'keys'

Here is where it gets weird:

type(song)
Traceback (most recent call last):
File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 3241, in runcode
locals = self.frame.f_locals)
File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 1583, in runcode
h_exec(code, globals=globals, locals=locals, module=module)
File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
\pythonlib\dbgp\client.py", line 520, in __init__
exec code in globals, locals
File "<console>", line 0, in <module>
TypeError: 'str' object is not callable
song
{"I Don't Wanna Stop": 1}
song.keys()
["I Don't Wanna Stop"]

For the complete script and data file, go to
http://members.dslextreme.com/users/...iebler/python/

Jul 20 '07 #1
Share this Question
Share on Google+
5 Replies


P: n/a
rpt_file.writelines('\t' + [song].keys() \
+ '\t' +
I get the following error:

Traceback (most recent call last):
AttributeError: 'list' object has no attribute 'keys'
All of these messages are correct. The first error is
AttributeError: 'list' object has no attribute 'keys'
You are converting the dictionary to a list on this line, and lists do
not have keys
rpt_file.writelines('\t' + [song].keys() \
---to a list <---
When you print it, you are printing a dictionary, so it does have
keys. Note the first line has braces, not brackets so it is a
dictionary. You might want to consider using a dictionary of classes,
with each class containing all of the data that is now in the
hodgepodge of dictionaries, or simply a list with item[0]=year,
item[1]=month, etc. This is an over-simplified version of using
classes to store data. There has to be more examples on the web.
Expand|Select|Wrap|Line Numbers
  1. .class my_class :
  2. ..   def __init__(self):
  3. ..      self.field_1 = "init field_1"
  4. ..      self.field_2 = 0
  5. ..
  6. ..objectList = []
  7. ..for j in range(0, 2):
  8. ..    objectList.append( my_class() )
  9. ..
  10. ..objectList[0].field_1= "Test [0] Field 1"
  11. ..objectList[0].field_2= "Data for Field #2 for [0]"
  12. ..objectList[0].field_3= "Data for Field #3 for [0]"  ## not in
  13. original
print "objectList[0] =", objectList[0].field_1, "---->",
\
objectList[0].field_2, "---->",
objectList[0].field_3
print "objectList[1] =", objectList[1].field_1, "---->",
objectList[1].field_2

Jul 20 '07 #2

P: n/a
You are converting the dictionary to a list on this line, and lists do
not have keys rpt_file.writelines('\t' + [song].keys() \
How am I converting it to a list?

Note the first line has braces, not brackets so it is a
dictionary.
Braces? What 1st line are you talking about?

Jul 20 '07 #3

P: n/a
Ignore my previous response. :p

I figured out what my problem was. I had [song].keys() when I really
meant song.keys() and really needed str(song.keys()). I just got a
little too bracket happy. :p
Jul 20 '07 #4

P: n/a
ro**********@gmail.com writes:
I have a data structure that looks like this:
[...]
rpt_file.writelines('\t' + [song].keys() + '\t' + [song].values() + '\n')
Forms the list [song] twice, attempting to call the 'keys()' method
and the 'values()' method of that list in turn...
I get the following error:

Traceback (most recent call last):
[...]
AttributeError: 'list' object has no attribute 'keys'
.... which doesn't exist.
Here is where it gets weird:

song
{"I Don't Wanna Stop": 1}
song.keys()
["I Don't Wanna Stop"]
Yes. A list doesn't have a 'keys' or 'values' method, a dict
does. 'song' is a dict. So why are you not calling the 'keys' method
of the 'song' object?

--
\ "If [a technology company] has confidence in their future |
`\ ability to innovate, the importance they place on protecting |
_o__) their past innovations really should decline." -- Gary Barnett |
Ben Finney
Jul 20 '07 #5

P: n/a
ro**********@gmail.com a écrit :
I have a data structure that looks like this:
(snip)
>
I get the following error:
(snip)
AttributeError: 'list' object has no attribute 'keys'
Already answered.
Here is where it gets weird:

type(song)
(snip)
TypeError: 'str' object is not callable
You code snippet started with:
if type == 'artist':

which implies you bound the name 'type' to a string. Then you try to use
the object bound to name 'type' as a callable. Python's bindings are
just name=>object mappings, and nothing prevents you to rebind a builtin
name. IOW, avoid using builtins types and functions as identifiers.

HTH

Jul 21 '07 #6

This discussion thread is closed

Replies have been disabled for this discussion.