访问嵌套列表和字典

时间:2019-07-21 17:51:59

标签: python-3.x list

availableDates.push(i, uniqPath, dateString, day)

我需要的答案是从await page.focus(`${tableData[0][0]} a`) 获取密钥,并为其值(列表)中的每个元素替换为A = {'a':1, 'b':2, 'c':3} B = {1:['a', 'b', 'c']} 的值,如下所示:

B

3 个答案:

答案 0 :(得分:0)

就地编辑B:

for key in B.keys():
    for i in range(len(B[key])):
        B[key][i] = A[B[key][i]]

创建一个新的D以便返回

D = B.copy()
for key in D.keys():
    for i in range(len(D[key])):
        D[key][i] = A[D[key][i]]

我测试了代码,它起作用了。

答案 1 :(得分:0)

这将为您工作:

A = {'a':1, 'b':2, 'c':3}
B = {1:['a', 'b', 'c']}

for key, value in B.items():  # loop in dict B
    # loop in every list in B, use items as key to get values from A
    # default to None if key doesn't exists in A and put it in a new temp list
    l = [A.get(x, None) for x in value]

    # Simplified version of line above
    # l = []
    # for x in value:
    #     l.append(A.get(x, None))

    D[key] = l  # use key of B as key and your new list value and add it to D

或者,如果您喜欢砍肉刀,那么:

# Doing same things as the last example but in one line
# which is hard to read and understand. Don't do this
D = {k: [A.get(x, None) for x in v] for k, v in B.items()}

答案 2 :(得分:0)

A [B [1] [0]]-将为您提供'a'的值

A [B [1] [1]]-将为您提供'b'的值,依此类推...

这是mt解决方案:

A = {'a':1, 'b':2, 'c':3}

B = {1:['a', 'b', 'c']}

D = {}

for key, value in B.items():
    D[key] = []
    for oneValue in value:
        D[key].append(A[oneValue]);
          
print D;