I'd like to pick out what I need from the dictionary list and save it on the list crying

Asked 2 years ago, Updated 2 years ago, 64 views

{ "code": "0000031852", "title": "Girls Ballet Tutu Zebra Hot Pink"}

In a dictionary list like this Find only those that contain the "Pink" string in the title How do I save the code value to the list? T.T

python dictionary

2022-09-22 20:55

2 Answers

I'm not sure I understood the problem correctly

list1 = [
{'code':'1', 'title':'black'},
{'code':'2', 'title':'pink'},
{'code':'3', 'title':'white'}
]

result = []
for x in list1 :
    if x['title'].find('pink')!=-1 :
        result.append(x['code'])
print(result)


2022-09-22 20:55

Try using the asq module. https://github.com/sixty-north/asq

Pandas is also a good module, but asq is also very convenient to use lightly.

list1 = [
{'code':'1', 'title':'black'},
{'code':'2', 'title':'pink'},
{'code':'3', 'title':'white'},
{'code':'4', 'title':'pink'}
]

from asq.initiators import query
r = query(list1).where(lambda item:item['title'] == 'pink').select(lambda item:item['code']).to_list()
print(r)

['2', '4']

The code is one line, but it's simple. That's exactly what the questioner wants.

Extract only the code value (.select(lambda item:item['title'] == 'pink') from the data (.query(list1))) where the title is pink.


2022-09-22 20:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.