473,407 Members | 2,312 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

Weird errors when trying to access a dictionary key

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
5 1967
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Neal | last post by:
Hi All Hope someone can help. Using WebRequest.Method = "POST" and ContentType = "application/x-www-form-urlencoded" I connect to a web application which then is expected to return me an XML...
2
by: harrymangurian | last post by:
I have VB.net standard installed on a stock DELL running XP. When I click on the icon whose target is: "C:\Program Files\Microsoft Visual Studio .NET\Common7 \IDE\devenv.exe" I get error...
2
by: msnews.microsoft.com | last post by:
I am currently trying to follow the Que Publishing exam guide to the Microsoft Exam 70-320. I followed the guide to a tee, but when I try to add a web reference to my server side soap extension it...
2
by: ticars | last post by:
I'm getting a weird error when trying to access a user control from within a base page during runtime. Here's what I have: I have a master page with a user control on it. I then have a few...
4
by: lawrence k | last post by:
I've a jpeg image that is 514k, which doesn't strike me as very large. Yet I'm running out of error when I try to resize it: Fatal error: Allowed memory size of 20971520 bytes exhausted (tried to...
10
by: teddysnips | last post by:
SQL Server 2000 (DDL below) If I try to run this code in QA: SET IDENTITY_INSERT tblAdminUsers ON INSERT INTO tblAdminUsers (fldUserID, fldUsername, fldPassword, fldFullname,
1
by: sshankar | last post by:
Hi, New to Stored procedure. Basically just installed DB2 v8.1.0.36 Was trying to build a stored procedure.. It is giving following error.. Looks like some error related to configuration...
2
by: Wayne | last post by:
I'm having a problem that I've seen before on XP and am now seeing on Vista. It started yesterday and I can't associate it with anything that I've done to the PC, like installing software etc. I...
1
by: Giuseppe.G. | last post by:
Hello Paavo, thanks for your kind reply. You may certainly be right, since it appears the author last worked on this toolkit back in 2006. I wish I knew more about templates, unfortunately I'm just...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.