将Python字典转换为列表列表

时间:2018-04-23 19:34:39

标签: python python-2.7

我有一个词典:

d={10:[2,"str1",4] , 20:[5,"str2",7] , 30:[8,"str3",10]}

我需要从这个词典中列出一个列表:

lst=[[10,2,"str1",4] , [20,5,"str2",7] ,[30,8,"str3",10]]

如果我使用lst = map(list,d.items()),那么键与值不在同一个列表中:

lst=[[10,[2,"str1",4]] , [20,[5,"str2",7]] ,[30,[8,"str3",10]]

我也试过这段代码:

for k,v in d.items():
    for i in v:
        lst=[]
        lst.append([k,i])

我不知道为什么,但我只得到这个:

lst=[[10,2]]

1 个答案:

答案 0 :(得分:4)

from tkinter.ttk import Treeview
from tkinter import *

class App:
    def __init__(self, master):
        self.master = master
        frame = Frame(master)

        master.geometry("{}x{}".format(master.winfo_screenwidth() - 100, master.winfo_screenheight() - 100))
        master.resizable(False, False)

        self.leftFrame = Frame(master, bg="#DADADA", width=375, relief=SUNKEN)
        self.leftFrame.pack_propagate(0)
        self.leftFrame.pack(side=LEFT, fill=Y, padx=1)

        # This table (TreeView) will display the partitions in the tab
        self.partitionsOpenDiskTree = Treeview(self.leftFrame, columns=("#"), show="headings", selectmode="browse", height=23)

        yscrollB = Scrollbar(self.leftFrame)
        yscrollB.pack(side=RIGHT, fill=Y)

        self.partitionsOpenDiskTree.column("#", width=50)
        self.partitionsOpenDiskTree.heading("#", text="#")
        self.partitionsOpenDiskTree.configure(yscrollcommand=yscrollB.set)

        # Bind left click on text widget to copy_text_to_clipboard() function
        self.partitionsOpenDiskTree.bind("<ButtonRelease-1>", lambda event, t=self.partitionsOpenDiskTree: self.copyTextToClipboard(t))

        # Adding the entries to the TreeView
        for i in range(3):
            self.partitionsOpenDiskTree.insert("", "end", i, values=(i), tags=str(i))

        self.partitionsOpenDiskTree.pack(anchor=NW, fill=Y)

    #todo: figure out where this is getting called and put in tree
    def copyTextToClipboard(self, tree, event=None):
        print(type(tree))
        # print(type(tree.partitionsOpenDiskTree))
        # triggered off left button click on text_field
        root.clipboard_clear()  # clear clipboard contents
        textList = tree.item(tree.focus())["values"]
        line = ""
        for text in textList:
            if line != "":
                line += ", " + str(text)
            else:
                line += str(text)

        root.clipboard_append(line)  # append new value to clipbaord
        print(line)

root = Tk()
app = App(root)
root.mainloop()

相同
lst=[]
lst.append([k,i])

在循环中不是很有用。

为了避免这些初始化错误,请像这样“压扁”你的字典(为密钥创建一个人工列表,只是为了能够将它添加到列表解析中的值):

lst=[k,i]

请注意,列表中的顺序无法保证,因为无法保证dicts中的顺序(除非您使用的是字典按字母顺序排列的版本,如CPython 3.6)