创建将一个键映射到另一个键的数据结构

时间:2017-08-24 15:59:31

标签: python python-3.x

我目前有两个list s:

[{'name': 'World', 'id': 44}, {'name': 'Hello', 'id': 43}]

[{'43': '1', '44': '2', 'id': 1}]

其中'43'等同于Hello,而'44'等同于World中的list。我想要做的是在第一个'name'中创建一个映射从'id'list(以及字典键)的数据结构,以便我可以编写一个测试断言来检查数据(在这种情况下为'1''2')存在。

对于Python来说,这是我刚刚努力的映射,所以对此的任何帮助都会非常感激。

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

我并不是100%清楚这个问题,但如果我有正确的想法,也许下面的内容可能有用吗?

# get the querysets
queryset1 = [{'name': 'World', 'content_type_id': 49, 'id': 44, 'order': 1, 'commit_id': 14}, {'name': 'Hello', 'content_type_id': 49, 'id': 43, 'order': 0, 'commit_id': 14}]
queryset2 = [{'id': 1, '43': '1', '44': '2'}]

# qs2 is a list so use the first item in this 
# example. Alternatively loop through each item
# it the queryset.
queryset2 = queryset2[0]

for item in queryset1:
    # the item id is an int and in qs2 is a string
    # so need to cast to a string
    str_id = str(item['id'])
    # try to retrieve the relevant value from qs2
    # based on the str_id
    qs2_number = queryset2.get(str_id)

    # if the number is not found then None is returned
    # hence the assertion is:
    assert qs2_number is not None

这有帮助吗?如果您只是试图声明该号码在queryset2或者您是否特别想要检查1或2,那么我不是100%,但您应该能够适应上述需求以适应您的需求。

或者,如果您可以提供更多详细信息,我可以帮助您进一步缩小解决方案范围。

修改

以下是您的评论,这是一个适合您的解决方案:

# querysets/lists
columns = [{'name': 'World', 'id': 44}, {'name': 'Hello', 'id': 43}]
rows = [{'43': '1', '44': '2', 'id': 1}]

# set variables
names_to_find = ['Hello', 'World']
target_row = rows[0]

for name_to_find in names_to_find:
    # create a list of column ids with the target name
    column_ids = [c['id'] for c in columns if c['name'] == name_to_find]

    for column_id in column_ids:
        # cast column id to a string
        str_column_id = str(column_id)
        # try to retrieve the relevant value from target row
        # based on the str_column_id
        target_row_value = target_row.get(str_column_id)
        # if the value is not found then None is returned
        # hence the assertion is:
        assert target_row_value is not None