繁体   English   中英

我可以在 python 的字典定义中循环一个数组吗?

[英]Can I loop an array inside a dictionary definition in python?

我正在尝试将数据推送到 Firebase 并且我能够遍历一个数组并在每个循环中推送信息。 但是我需要在其中添加一些图片(所以这就像在字典定义中循环一个数组)。 我有一个数组中的所有链接。 到目前为止,这是我的代码。

def image_upload():
for i in range(len(excel.name)):
    doc_ref = db.collection('plans').document('doc-name').collection('collection-name').document()
    doc_id = doc_ref.id
    data = {
        'bedroomLocation': excel.bedroomLocation[i],
        'bedrooms': excel.bedrooms[i],
        'brand': excel.brand[i],
        'catalog': excel.catalog[i],
        'category': excel.category[i],
        'code': excel.code[i],
        'depth': excel.depth[i],
        'description': excel.description[i],
        'fullBaths': excel.fullBaths[i],
        'garage': excel.garage[i],
        'garageBays': excel.garageBays[i],
        'garageLocation': excel.garageLocation[i],
        'garageType': excel.garageType[i],
        'date': firestore.SERVER_TIMESTAMP,
        'id': doc_id,
        'halfBaths': excel.halfBaths[i],
        'laundryLocation': excel.laundryLocation[i],
        'name': excel.name[i],
        'onCreated': excel.onCreated[i],
        'productType': excel.productType[i],
        'region': excel.region[i],
        'sqf': excel.sqf[i],
        'state': excel.state[i],
        'stories': excel.stories[i],
        'tags': [excel.tags[i]],
        'width': excel.width[i],
    }
    doc_ref.set(data)

这很好用,但我真的不知道如何遍历链接数组。 这是我在上面复制的块下面尝试的。

for j in range(len(excel.gallery)):
    if len(excel.gallery[j]) != 0:
        for k in range(len(excel.gallery[j])):
            data['gallery'] = firestore.ArrayUnion(
                [{'name': excel.gallery[j][k][0], 'type': excel.gallery[j][k][1],
                  'url': excel.gallery[j][k][2]}])
            print(data)
doc_ref.set(data)

len(excel.gallery)len (excel.name) 的长度相同,但每个 j position 具有不同数量的链接。 如果我在数据定义中声明图库并使用 ArrayUnion 并预定义多个信息,它可以正常工作,但我需要使用该数组将信息推送到 Firebase。

当你说“我有一个数组中的所有链接”时,我有点困惑。 我们可以看看那个数组和你在找什么样的 output 吗?

还假设 excel.gallery 是一个字典,您可以使用 items() function 大量清理代码。

for j, k in excel.gallery.items():
    if k:
        data['gallery'] = firestore.ArrayUnion([{'name': k[0], 'type': k[1], 'url': k[2]}])
        print(data)

doc_ref.set(data)

excel.gallery 实际上是一个矩阵,不是字典。 这是此 [[['Images/CFK_0004-Craftmark_Oakmont_Elevation_1.jpeg', 'Elevation', 'url example from firebase'], .... 的示例输出之一,它适用于每个文件。 我正在测试 8 张图像和 2 个计划。 所以在这种情况下,我的矩阵是 2x4。 但在 position 中,如果没有匹配,则可能没有任何文件。 我正在寻找的是在数据被推送之前(或在顺序无关紧要之后)添加该计划的所有网址。

这有效:

'gallery': firestore.ArrayUnion(
            [{'name': 'Example Name', 'type': 'Elevation',
              'url': 'Example url'},
             {'name': 'Example Name2', 'type': 'First Floor',
              'url': 'Example url2'}])

但我需要填充通过 excel.gallery 循环的字段

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM