Yatin Hasija
Yatin Hasija

Reputation: 33

striping elements from string inside of list(python)

I am having a data set which is from MongoDB and looks like:

info=['[{"key1":"value1","key2":"value2","key3":[{"another_key":"another_value"}]}]',
'[{"key1":"valuex","key2":"valuex","key3":[{"another_keyx":"another_valuex"}]}]',
'[{"key_1":"valuex","key2":"valuex","key3":[{"keyx":"valuex"}]}]']

Its all in string so I am trying to use this method:

city=[]
    for index, row in csv.iterrows():
    
    if 'key1' in str(row['ip_info']):
        city.append() #the value of key1 # some logic I don't know how to code
                       # but it is like if we find "key1" in this string then slice a portion which start from key1": and end at ",
    else:
        city.append(0)

Expected output need to be like:

city=["value1","valuex",0]

I am trying to implement the logic as when "key1" is found in string then we will slice the string from "key1":(as starting point) and end at ",(which is right after the value of that key, so that we can get what's between those starting and ending points.

Upvotes: 0

Views: 24

Answers (1)

Neeraj
Neeraj

Reputation: 997

I Hope this is what you are trying to achieve:

city = []

for element in info:
    inner_dict = eval(element)[0]
    if "key1" in inner_dict.keys():
        city.append(inner_dict["key1"])
    else:
        city.append(0)

print(city)

# OUTPUT:
# ['value1', 'valuex', 0]

Upvotes: 1

Related Questions