Shantanu
Shantanu

Reputation: 867

Python: How to filter through multiple dictionaries of lists?

I have the following dictionaries. I want to filter through them to generate a string as output. What is the best way to achieve this?

uw = {
    "name": ["uw1", "uw2", "uw3", "uw4"],
    "code": [1135, 1134, 1133, 1132],
}

tp = {
    "name": ["tp1", "tp2", "tp3", "tp4"],
    "code": [1000, 1001, 1002, 1003]
}

uw_val = "uw3"
tp_val = "tp4"

Output

1133-1003

Upvotes: -1

Views: 50

Answers (2)

Nikita Zhuikov
Nikita Zhuikov

Reputation: 1062

You may use zip function

d1 = dict(zip(uw['name'], uw['code']))
d2 = dict(zip(tp['name'], tp['code']))

print(f'{d1["uw3"]}-{d2["tp4"]}')

Upvotes: 2

DevScheffer
DevScheffer

Reputation: 499

Use index() and if use join convert the number to string

uw = {
    "name": ["uw1", "uw2", "uw3", "uw4"],
    "code": [1135, 1134, 1133, 1132],
}

tp = {
    "name": ["tp1", "tp2", "tp3", "tp4"],
    "code": [1000, 1001, 1002, 1003]
}

uw_val = "uw3"
tp_val = "tp4"

idx_uw=uw['name'].index(uw_val)
res_uw=uw['code'][idx_uw]
idx_tp=tp['name'].index(tp_val)
res_tp=tp['code'][idx_tp]
res=[str(res_uw),str(res_tp)]
print('-'.join(res))

Upvotes: 1

Related Questions