如何将dict值从列表转换为元组

时间:2017-04-24 06:54:43

标签: python list dictionary for-loop tuples

我需要将列表中的字典值转换为列表中的元组。

我的代码如下:

string = "bi2gger 1is 00ggooder"

string.gsub(/./) { |s| s=='g' ? 'g' : ' ' }
  #=>    "   gg         gg     " 

目前,我的输出是具有以下格式的字典:

import io

opened_infocsv = io.StringIO('''"ID","Name","Type 1","Type 2","Generation","Legendary"
720,"HoopaHoopa, Confined","Psychic","Ghost",6,"TRUE"
1,"Bulbasaur","Grass","Poison",1,"FALSE"
681,"Aegislash, (Blade Form)","Steel","Ghost",6,"FALSE"
413,"Wormadam, Plant","Bug","Grass",4,"FALSE"
643,"Reshiram","Dragon","Fire",5,"TRUE"
678,"Meowstic, Male","Psychic","",6,"FALSE"''')

def read_info_file(filename):
    idb = {} #Declares empty dict to be written to.
    #opened_infocsv = open(filename, 'r') #opens an argued .csv file witH INFO format.
    info_string = opened_infocsv.readlines()

    #opened_infocsv.close()
    for i in range(1,len(info_string)):
        splitline=info_string[i].replace("\n",'').replace('"','').split(',')
        for loc,i in enumerate(splitline):
            if i=="":
                splitline[loc]=None

        if len(splitline)==7:
            splitline[1]=splitline[1]+","+splitline.pop(2)
            splitline[0],splitline[4]=int(splitline[0]),int(splitline[4])
        if len(splitline)==6:
            splitline[0],splitline[4]=int(splitline[0]),int(splitline[4])
        if splitline[5] == "TRUE":
            splitline[5]= True
        else:
            splitline[5] = False

        idb[splitline.pop(1)] = splitline
    print(idb)

我想要发生的是要转换为元组的值列表。

我尝试了{'HoopaHoopa, Confined': [720, 'Psychic', 'Ghost', 6, True]} ,但它似乎无法正常工作。

最后,我需要能够在最后一行tuple(idb.values())之后添加解决方案,因为我需要能够在转换之前弹出列表

1 个答案:

答案 0 :(得分:0)

这是非常基本的,只需构建一个新的字典,其中每个值都已转换为元组并重新绑定旧字典的名称。

这是一个简短的演示:

>>> d = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> d = {key:tuple(lst) for key, lst in d.items()}
>>> d
{'a': (1, 2, 3), 'b': (4, 5, 6)}

我使用了字典理解。如果您对这些代码感到不舒服,以下代码可以实现相同的目标。

>>> d = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> new_d = {}
>>> for key, lst in d.items():
...     new_d[key] = tuple(lst)
... 
>>> d = new_d
>>> d
{'a': (1, 2, 3), 'b': (4, 5, 6)}

编辑:我刚刚意识到我的回答是不完整的,因为在帖子的最后一行还有一个问题。我并不真正关注你在那里谈论的内容,所以我现在就把答案保留下来。