简体   繁体   English

Python将列表转换为具有键值的字典

[英]Python convert list into Dictionary with key value

I am getting json response from SOLR via PySolr , everything works fine, just that Facet fields are coming in inconsistent format , below is the facet fields 我通过PySolr从SOLR得到json响应,一切正常,只是Facet字段格式不一致,下面是facet字段

LocalityId = [ "14008",1,"14293",4,]

Now I need to convert the above list into Key-Value pair (Dictionary), likewise 现在,我需要将上述列表转换为键值对(字典),同样

LocalityId = {"14008":"1", "14293":"4"}

How to achieve this with python ? 如何用python实现呢?

Edit : Yes I know its not standard list format , but I didnt created it , blame solr 编辑:是的,我知道它不是标准列表格式,但是我没有创建它,怪罪于solr

Edit : Why -1 , stackoverflow has become a place for revenge and random outburst! 编辑:为什么-1,stackoverflow已成为复仇和随机爆发的地方! tell me here folk where I am wrong ?? 在这里告诉我我错了吗?

Using slicing and zip you can create a dict like so assuming your list is called l : 使用slicingzip您可以创建一个像这样的字典,假设您的列表名为l

dict(zip(l[::2], l[1::2]))

l[::2] will get every 2nd element of the list starting at index 0, in the same manner l[1::2] get every 2nd element starting at index 1. l[::2]将以索引0开始获取列表的每个第二元素,同样的方式l[1::2]将以索引1开始获取每个第二元素。

l = ["14008", 1, "14293", 4]
l[::2] # ['14008', '14293']
l[1::2] # [1, 4]

These two lists are then zip ped together to create the dict. 然后将这两个列表zip在一起以创建字典。

EDIT As suggested in the comments the keys should be strings as well so we can use map to transform them. 编辑如注释中所建议,键也应该是字符串,因此我们可以使用map进行转换。 The code will become: 该代码将变为:

dict(zip(l[::2], map(str, l[1::2])))

You can use zip and dict for convert to your list to expected dictionary : 您可以使用zipdict将列表转换为所需的字典:

>>> l=[ "14008",1,"14293",4,]
>>> dict(zip(l[::2],l[1::2]))
{'14008': 1, '14293': 4}

Another way is to use dict comprehension. 另一种方法是使用dict理解。

l = ["14008", 1, "14293", 4]
{l[i*2]: l[i*2+1] for i in range(int(len(l)/2))}

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

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