简体   繁体   中英

Slicing string values in each dict from list of dicts?

I feel like the answer to this question is not very complex, yet I can't for the life of me figure it out.

I have a list of dictionaries. The keys in the dictionary are integers (0, 1, 2) . The values are strings containing extraneous information, with relevant information in brackets. I want to slice the strings such that the content between the brackets is the new value. I want to update each dictionary in this way, and then pack each dictionary back into its list.

Let's pretend this is what I have:

Original = [{1: 'xxx [pear] yyy', 2: 'xxx [apple] zzz'}, {0: 'aaa [cat] yyy', 1: 'bbb [dog] zzz'}]

This is what I want my function to return:

[{1: 'pear', 2: 'apple'}, {0: 'cat', 1: 'dog'}]

How would I go about doing this? Edit: I know how to slice the string as follows:

slicev = v.split('[', 1)[1].split(']')[0]

def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end]
    except ValueError:
        return ""

original = [{1: "xxx [pear] yyy", 2: "xxx [apple] zzz"}, {0: "aaa [cat] yyy", 1: "bbb [dog] zzz"}]

for dct in original:
    for key in dct:
        dct[key] = find_between(dct[key], "[", "]")

You could use regular expression

import re
Original = [{1: "xxx [pear] yyy", 2: "xxx [apple] zzz"}, {0:" aaa [cat] yyy", 1: "bbb [dog] zzz"}]
for item in Original:
    for key in item:
         item[key]= re.findall("\[(.*?)\]",item[key])[0]

print Original

The result

[{1: 'pear', 2: 'apple'}, {0: 'cat', 1: 'dog'}]

Beware that this will change the original list.

I think re module can help you:

import re

original = [{1: 'xxx [pear] yyy', 2: 'xxx [apple] zzz'},
            {0: 'aaa [cat] yyy', 1: 'bbb [dog] zzz'}]

data = [{k: re.search(r'\[(.*?)\]', v).group(1) for k, v in d.items()}
        for d in original]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM