lwwwr lwwwr - 3 months ago 14
Python Question

Difference between coding of dictionaries in python versions

I have following codestrings:

#coding: utf
import json
import base64
from lxml import html, etree
import urllib2

somedictionary={}
url1="someurl1"
base64string = base64.b64encode('%s:%s' % ('user', 'pass'))
xml1request = urllib2.Request(url1)
xml1request.add_header("Authorization", "Basic %s" % base64string)
xml1=etree.parse(urllib2.urlopen(xml1request))
somelist=xml1.xpath("//list1//a/text()")

for element in somelist:
url2="part of url2"+element+"part of url2"
xml2request=urllib2.Request(url2)
xml2request.add_header("Authorization", "Basic %s" % base64string)
xml2=etree.parse(urllib2.urlopen(xml2request))

b=xml2.xpath("//list2//b/text()")
c=xml2.xpath("//list2//c/text()")
d=xml2.xpath("//list2//d/text()")
e=xml2.xpath("//list2//e/text()")
somedictionary[key.index(element)]={key.index(element):{"a": element, "b": b, "c": c, "d": d, "e": e}}
#json.dump(bamboo, open("12345.txt","w"))


in python 3.4.0 it works.
But in python 2.7.10 it returns me an error:

Traceback (most recent call last):
File "C:\Users\user\11.py", line 25, in <module>
somedictionary[key.index(element)]={key.index(element):{"a": a, "b": b, "c": c, "d": d, "e": e}}
NameError: name 'key' is not defined
>>>


Variables
b
,
c
,
d
,
e
announced in cycle;
somedictionary
announced before cycle
I don't found some information about this moment in pythondocks
How to fix it, if it works in python 3.4.0?

Answer

The only way it could work in python3 and not python2 is if somelist is empty in python3 so you never reach the code inside the loop:

In [20]: l = []

In [21]: for ele in l: 
           print(not_defined) # never reach here 
   ....:     

In [22]: l = [1]

In [23]: for ele in l:
           print(not_defined) # loop once so we get here and error
   ....:     
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-23-6e24b65bf7e0> in <module>()
      1 for ele in l:
----> 2            print(not_defined)
      3 

NameError: name 'not_defined' is not defined

You never defined the name key anywhere so bar somelist is empty you would get a NameError as above in both python2 and python3.

So you have two problems, in python3 your code is not finding anything, if it did you still have the key issue as you don't define it anywhere so you need to figure out what key should be and debug your python3 logic.