Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

Python to find dict in a list with particular key

I have an array of lists with dicts as below:

[{'key': 'Platform', 'value': 'Test'}, {'key': 'Name', 'value': 'Test1'}, {'key': 'APICall', 'value': 'post'}]
[{'key': 'Platform', 'value': 'Test1'}, {'key': 'APICall', 'value': 'Get'}]
[{'key': 'Platform', 'value': 'Test2'}, {'key': 'Name', 'value': 'Test2'}, {'key': 'APICall', 'value': 'post'}]

for this array I would like to get the lists if keys Platform and Name present. So I would like to get [{'key': 'Platform', 'value': 'Test'}, {'key': 'Name', 'value': 'Test1'}, {'key': 'APICall', 'value': 'post'}] and [{'key': 'Platform', 'value': 'Test2'}, {'key': 'Name', 'value': 'Test2'}, {'key': 'APICall', 'value': 'post'}]

I don't know how to achieve this in one most effective way? I did a very simplistic way which is working, but in the future, if the list count grows then it might take a longer time. Is there any simple and effective way to achieve this?

for arr_keys in arr:
            if arr_keys['key'] == "Platform":
                platform = arr_keys['value']
            if arr_keys['key'] == "Name":
                Name = arr_keys['value']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The only improvement you can make without changing the formatting of the input is to break out of the loop once the keys 'Platform' and 'Name' are encountered.

platform = None
name = None
for arr_keys in arr:
    if arr_keys['key'] == "Platform":
        platform = arr_keys['value']
    if arr_keys['key'] == "Name":
        name = arr_keys['value']
    if platform is not None and name is not None:
        print(arr)
        break

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...