简体   繁体   English

将字符串列表转换为字典

[英]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我尝试过 ast 库和 JSON.loads 但徒劳无功

Simple one-liner using a dict comprehension:使用 dict 理解的简单单行:

{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. zip(arr[::2],arr[1::2])迭代数组对,并且str.split为键和值提取正确的值。

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).给定一个形状为[' key=aKey', ' age=valueForAKey', ' key=bKey', ...]的列表arr (注意每个列表元素开头的空格)。

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在这里试试: 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.如果前导空格的数量不一致(如您给出的示例中),您可以使用lstrip()方法删除前导空格。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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