Weird errors when trying to access a dictionary key

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • robinsiebler@gmail.com

    #1

    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.writel ines('Song Summary for ' + artist + '\n\n')
    for year in sorted(rpt_date s):
    for week in sorted(rpt_date s[year]):
    for date in sorted(dates[year][week]):
    if artist in dates[year][week][date]:
    report.append(d ate)
    for song in sorted(dates[year][week][date]
    [artist]):
    rpt_file.writel ines('\t' + [song].keys() \
    + '\t' +
    [song].values() + '\n')


    I get the following error:

    Traceback (most recent call last):
    File "C:\Program Files\ActiveSta te Komodo 3.5\lib\support \dbgp
    \pythonlib\dbgp \client.py", line 1843, in runMain
    self.dbg.runfil e(debug_args[0], debug_args)
    File "C:\Program Files\ActiveSta te 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\ActiveSta te Komodo 3.5\lib\support \dbgp
    \pythonlib\dbgp \client.py", line 596, in __init__
    execfile(file, globals, locals)
    File "C:\scripts\pyt hon\Songs\song_ report.py", line 136, in <module>
    if __name__== '__main__': main()
    File "C:\scripts\pyt hon\Songs\song_ report.py", line 134, in main
    print_rpt(optio ns.type, rpt_dates, dates, args)
    File "C:\scripts\pyt hon\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\ActiveSta te Komodo 3.5\lib\support \dbgp
    \pythonlib\dbgp \client.py", line 3241, in runcode
    locals = self.frame.f_lo cals)
    File "C:\Program Files\ActiveSta te 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\ActiveSta te 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


  • Zentrader

    #2
    Re: Weird errors when trying to access a dictionary key

    rpt_file.writel ines('\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.writel ines('\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.
    Code:
    .class my_class :
    ..   def __init__(self):
    ..      self.field_1 = "init field_1"
    ..      self.field_2 = 0
    ..
    ..objectList = []
    ..for j in range(0, 2):
    ..    objectList.append( my_class() )
    ..
    ..objectList[0].field_1= "Test [0] Field 1"
    ..objectList[0].field_2= "Data for Field #2 for [0]"
    ..objectList[0].field_3= "Data for Field #3 for [0]"  ## not in
    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

    Comment

    • robinsiebler@gmail.com

      #3
      Re: Weird errors when trying to access a dictionary key

      You are converting the dictionary to a list on this line, and lists do
      not have keys rpt_file.writel ines('\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?

      Comment

      • robinsiebler@gmail.com

        #4
        Re: Weird errors when trying to access a dictionary key

        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


        Comment

        • Ben Finney

          #5
          Re: Weird errors when trying to access a dictionary key

          robinsiebler@gm ail.com writes:
          I have a data structure that looks like this:
          [...]
          rpt_file.writel ines('\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

          Comment

          • Bruno Desthuilliers

            #6
            Re: Weird errors when trying to access a dictionary key

            robinsiebler@gm ail.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

            Comment

            Working...