AttributeError: 'dict' object has no attribute 'iteritems'

This is the place for queries that don't fit in any of the other categories.

AttributeError: 'dict' object has no attribute 'iteritems'

Postby RexKing » Mon Sep 09, 2013 2:36 am

Hello, i have started learning python recently and had this problem on a code im working on.
The code is meant to implement an application that do simple operations in a databank server, in the case MySQL.
I'm following the tutorial on MySQL page, and am currently stuck at this page http://dev.mysql.com/doc/refman/5.7/en/ ... e-ddl.html
due to the error AttributeError: 'dict' object has no attribute 'iteritems'.

Here is the complete code:
Code: Select all
from __future__ import print_function
import mysql.connector
from mysql.connector import errorcode



def connect_database(v1,v2,v3):
    try:
      cnx = mysql.connector.connect(user='root',
                                    password='108414',
                                    host='localhost')
      return (cnx)
    except mysql.connector.Error as err:
      if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
        exit(1)
      elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exists")
        exit(1)
      else:
        print(err)
        exit(1)

def create_cursor(cnx):
    csr = cnx.cursor()
    return (csr)

def create_database(cnx,DB_NAME,csr):
    try:
        csr.execute(
            "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
    except mysql.connector.Error as err:
        print("Failed creating database: {}".format(err))
        exit(1)
    try:
        cnx.database = DB_NAME   
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_BAD_DB_ERROR:
            create_database(csr)
            cnx.database = DB_NAME
        else:
            print(err)
            exit(1)

def create_table(cursor):


    TABLES = {}

    TABLES['empregados'] = (
        "CREATE TABLE `empregados` ("
        " `emp_nu` int(11) NOT NULL AUTO_INCREMENT,"
        " `data_nasc` date NOT NULL,"
        " `nome` varchar(20) NOT NULL,"
        " `sobrenome` varchar(30) NOT NULL,"
        " `sexo` enum('M','F') NOT NULL,"
        " `data_de_trab` date NOT NULL,"
        " PRIMARY KEY ('emp_nu')"
        ") ENGINE=InnoDB")

    TABLES['clientes'] = (
        "CREATE TABLE `clientes` ("
        " `cliente_nu` char(4) NOT NULL,"
        " `nome` varchar(20) NOT NULL,"
        " `sobrenome` varchar(30) NOT NULL,"
        " `sexo` enum('M','F') NOT NULL,"
        " `cpf` int(11) NOT NULL,"
        " `data_nasc` date NOT NULL,"
        " PRIMARY KEY (`cliente_nu`, `cpf`)"
        ") ENGINE=InnoDB")

    TABLES['salarios'] = (
        "CREATE TABLE `salarios` ("
        " `emp_nu` int(11) NOT NULL,"
        " `salario` int(11) NOT NULL,"
        " `da_data` date NOT NULL,"
        " `ate_data` date NOT NULL,"
        " PRIMARY KEY (`emp_nu`, `da_data`), KEY `emp_nu` (`emp_nu`),"
        " CONSTRAINT `salarios_ibfk_1` FOREIGN KEY (`emp_no`)"
        "   REFERENCES `empregados` (`emp_no`) ON DELETE CASCADE"
        ") ENGINE=InnoDB")

    TABLES['produto'] = (
        "CREATE TABLE `produto` ("
        " `prod_nu` int(11) NOT NULL,"
        " `nome` varchar(30) NOT NULL,"
        " `data_lcm` date NOTNULL,"
        " `preco` int(11) NOT NULL,"
        " PRIMARY KEY (prod_nu)"
        ") ENGINE=InnoDB")
   
    for name, ddl in TABLES.iteritems():
       
        try:
            print("Creating table {}: ".format(name), end='')
            cursor.execute(ddl)
        except mysql.connector.Error as err:
            if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
                print("already exists.")
            else:
                print(err.errmsg)
        else:
            print("OK")
                     
               

       

menu = 0
teste = 0
cx = 0

while menu != 99:
    print("""
    ----- Menu Banco MARK, v.1.00, MySQL, VR -----

    1.Conectar com servidor de banco de dados local.
    2.Criar Banco.
    3.Criar Tabelas da Loja.
    99.Sair.

        """)

    menu = input("Digite sua opcao: ")
    if menu == "1":
        v1 = input("Digite nome do usuario: ")
        v2 = input("Digite password: ")
        v3 = input("Digite o host: ")
        cx = connect_database(v1,v2,v3)
        teste = 1
        cursor = create_cursor(cx)

    elif menu == "2":
        if cx == 0:
            print("""
                  Nenhum banco de dados conectado.
                  """)
        else:
            DB_NAME = input("Digite nome do banco: ")
            create_database(cx, DB_NAME, cursor)
           
    elif menu == "3":
        if cx == 0:
            print("""
                  Nenhum banco de dados conectado.
                  """)
        else:
            create_table(cursor)
           
       
    if menu == "99":
        if teste == 1:
            cursor.close()
            cnx.close()
            break
        else:
            break



The error occur after using option 3 on the menu (create table function).
The traceback:
Code: Select all
Traceback (most recent call last):
  File "C:/Python33/Archieve/MySQL-teste6.py", line 190, in <module>
    create_table(cursor)
  File "C:/Python33/Archieve/MySQL-teste6.py", line 92, in create_table
    for name, ddl in TABLES.iteritems():
AttributeError: 'dict' object has no attribute 'iteritems'


Thanks for any help.
RexKing
 
Posts: 2
Joined: Mon Sep 09, 2013 2:24 am

Re: AttributeError: 'dict' object has no attribute 'iteritem

Postby metulburr » Mon Sep 09, 2013 3:36 am

File "C:/Python33

if you are using python 3.x, why are you writing 2.x code?

in 3.x it's just
Code: Select all
dict.items()
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1470
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: AttributeError: 'dict' object has no attribute 'iteritem

Postby RexKing » Mon Sep 09, 2013 4:33 am

Do i still need the cursor after that? Or the table will be implemented?
RexKing
 
Posts: 2
Joined: Mon Sep 09, 2013 2:24 am

Re: AttributeError: 'dict' object has no attribute 'iteritem

Postby metulburr » Mon Sep 09, 2013 7:22 am

You don't have to PM me. You can post on the forum. It will help others who are searching the same thing.

The documentation can be checked offline of any 3rd party module via the interpreter and python's builtin help() with the computer that has that 3rd party module installed. Which can be used to search the doc for the entire module or a specific method.

Code: Select all
metulburr@ubuntu:~$ python3
Python 3.3.1 (default, Apr 17 2013, 22:30:32)
[GCC 4.7.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from bs4 import BeautifulSoup
>>> help(BeautifulSoup)

>>> help(BeautifulSoup.find)

>>>

and what you don't see is the documentation that i exited to get back to the interpreter's prompt
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1470
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 3 guests