473,238 Members | 1,505 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,238 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 1956
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.