简体   繁体   中英

Converting a list of strings to dictionary

['key=IAfpK', ' age=58', ' key=WNVdi', ' age=64', ' key=jp9zt', ' age=47', ' key=0Sr4C', ' age=68', ' key=CGEqo', ' age=76', ' key=IxKVQ', ' age=79', ' key=eD221', ' age=29']

I got the following list, i need to convert it to a dictionary,like

{"IAfpK":58,"WNVdi":,"64":,.....}

I have tried ast library and JSON.loads but in vain

Simple one-liner using a dict comprehension:

{x.split("=")[1]: int(y.split("=")[1]) for x,y in zip(arr[::2],arr[1::2])}

zip(arr[::2],arr[1::2]) iterates over pairs of the array, and str.split extracts the correct value for the key and value.

If you know that your list is always following this exact format and order, just loop through the list:

mydict = {}
for element in mylist:
   if "key=" in element:
      mydict[element.replace("key=", "")] = None
   else:
      mydict[mydict.keys()[-1]] = int(element.replace("age=", ""))

Given you a list arr of the shape [' key=aKey', ' age=valueForAKey', ' key=bKey', ...] (note the space at the start of each list element).

You can use this dictionary comprehension to extract the matching key and values and build the resulting dictionary.

{arr[i][5:]: arr[i+1][5:] for i in range(0, len(arr), 2)}

Try it out here: https://www.online-python.com/iGI3A2YEnr

If the number of leading spaces is inconsistent (as in the example you gave), you can use the lstrip() method to remove the leading spaces.

{arr[i].lstrip()[4:]: arr[i+1].lstrip()[4:] for i in range(0, len(arr), 2)}

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