【问题标题】:How to read a tuple inside dictionary如何读取字典中的元组
【发布时间】:2016-02-11 15:20:41
【问题描述】:

我的问题是我收到这个但在字符串中

obj = {"rnc": "44444044444",
         "cliente": "EMPRESA S.A.",
         "ncf": "1234567890123456789",
         "ncf_ref": "0987654321098765432",
         "tipo": "FacturaConsumidorFinal",     # Ver clase ReceiptEnum para valores permitidos
         "logo": false,
         "lineas": [{
             "descripcion": ["Linea 1", ..., "Linea 10"],
             "cantidad": 2,
             "importe": 12.00,
             "itbis": 13.0,
             "tipo_pago": "LineaVenta",        # Ver clase ReceiptItemEnum para valores permitidos
             "qtyxprice": True,
             "promocion": False"
            }],
         "pagos": [{
            "tipo": 1,                         # valor entre 1 y 14, según tipos de pago configurados
            "importe": 1200.00,
            "cancelado": False,
            "descripcion": ["linea 1", "linea 2", "lines 3"],
         }],
         "descuentos": [{                      # descuento o recargo global
            "descripcion": "lalalala",
            "importe": 1200.00
         }],
         "densidad": "ppp180x180"              # ver clase PrinterDensity para valores permitidos
        }

我使用

转换为字典
import ast
linea = ast.literal_eval(obj)

我试图在 lineas['importe'] 内部读取,当然使用 int 将值 12.00 更改为 1200,我知道该怎么做,只需乘以 100 例如

#12.00
int(12.00*100) = 1200 #they always need to end with '00'
int(2*100) = 200

但我不知道如何使用 linea['itbis]..pagos['importe'] 和 descuentos['importe'] 到达那里,最后它会像这样输出。

{"rnc": "44444044444",
     "cliente": "EMPRESA S.A.",
     "ncf": "1234567890123456789",
     "ncf_ref": "0987654321098765432",
     "tipo": "FacturaConsumidorFinal",     # Ver clase ReceiptEnum para valores permitidos
     "logo": false,
     "lineas": [{
         "descripcion": ["Linea 1", ..., "Linea 10"],
         "cantidad": 2,
         "importe": 1200,    #<----- here(12.00)
         "itbis": 1300,      #<----- here(13.00)
         "tipo_pago": "LineaVenta",        # Ver clase ReceiptItemEnum para valores permitidos
         "qtyxprice": True,
         "promocion": False"
        }],
     "pagos": [{
        "tipo": 1,                         # valor entre 1 y 14, según tipos de pago configurados
        "importe": 120000,     #<----- here (1200.00)
        "cancelado": False,
        "descripcion": ["linea 1", "linea 2", "lines 3"],
     }],
     "descuentos": [{                      # descuento o recargo global
        "descripcion": "lalalala",
        "importe": 120000   #<----- here (1200.00)
     }],
     "densidad": "ppp180x180"              # ver clase PrinterDensity para valores permitidos
    }

我正在尝试

for k,v in obj.items():
for thing in v:
    print v

但我得到一个错误和结束 回溯(最近一次通话最后): 文件“”,第 2 行,在 TypeError: 'bool' 对象不可迭代

感谢您阅读这篇长长的解释 x_X

【问题讨论】:

  • 嗯,你的一些值是False,而且,正如错误消息所说,你不能迭代布尔值。
  • 看起来你的 dict 值是一个包含单个元素的列表,它是一个 dict。您应该能够使用linea["lineas"][0]["importe"] 访问12.00 条目。然后你可以做任何你喜欢的事情。
  • 我尝试使用 linea["lineas"][0]["importe"] 但我得到了这个 TypeError: tuple indices must be integers, not str

标签: python dictionary int tuples


【解决方案1】:

您会收到此错误,因为并非 dict 中的所有值都是可迭代的。如果您想遍历整个 dict 以找到您描述的值(即您不确切知道 dict 的内容),您可以执行以下操作:

for k,v in obj.items():
    if hasattr(v, '__iter__'):
        for thing in v:
            print thing
    else:
        print v

if hasattr(v, '__iter__'): 行将判断您的项目是否可迭代(请参阅此问题 In Python, how do I determine if an object is iterable?

【讨论】:

  • 谢谢你......但是我如何才能访问那些我猜它调用列表来执行操作的......?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 2020-09-21
相关资源
最近更新 更多