简体   繁体   English

从2个键和2个元组的字典创建排序列表

[英]Create sorted list from dictionary of 2 keys and 2 tuples

Trying to create a function which I can use to create a sorted list from two keys and two tuples as the values. 试图创建一个函数,我可以使用它来创建两个键和两个元组作为值的排序列表。 I am having an issue somewhere with my "for" loop in that it will for some reason only print the key and the first tuple. 我的“ for”循环在某处出现问题,由于某种原因,它将仅打印键和第一个元组。 Somehow, the second tuple never gets passed through the sorter. 不知何故,第二个元组永远不会通过排序器。

def printDictionary(dictionaryParm):
    for x in dictionaryParm:
    header = []
    header.append(x)

    for y in dictionaryParm.values():
       value = list(y)
       value.sort()

    output = header + value
    for item in output:
        print item

dictionaryTest = dict()
dictionaryTest["Key 1"] = ("234","123","345")
dictionaryTest["Key 2"] = ("456","678","567")

printCourseDictionary(dictionaryTest)

My guess is that there is an issue somewhere with the "for y" statement, but after a few versions, having included breaks and whatnot, I still cannot get the output correct. 我的猜测是,“ for y”语句在某处存在问题,但是经过几个版本(包括中断和其他内容)后,我仍然无法获得正确的输出。

Ideally, output should be something like this: 理想情况下,输出应如下所示:

Key 1
123
234
345
Key 2
456
567
678

Thoughts? 有什么想法吗?

Your code have some indentation problems, but if I understood you right you need following code 您的代码有一些缩进问题,但如果我理解正确,则需要以下代码

def printDictionary(dictionaryParm):
    for x in dictionaryParm:
        header = [x]

        value = list(dictionaryParm[x])
        value.sort()

        output = header + value
        for item in output:
            print(item)

dictionaryTest = dict()
dictionaryTest["Key 1"] = ("234","123","345")
dictionaryTest["Key 2"] = ("456","678","567")

printDictionary(dictionaryTest)

Code output 代码输出

Key 2
456
567
678
Key 1
123
234
345

Issue is @ indentation in loop where in value to be sorted and added. 问题是@缩进循环,在其中对值进行排序和添加。 is this address your issue ?? 这是您的问题吗? def printDictionary(dictionaryParm): for k, y in dictionaryParm.items(): value = list(y) value.sort() output = ([k]+ value) for it in output: print (it) dictionaryTest = dict() dictionaryTest["Key 1"] = ("234","123","345") dictionaryTest["Key 2"] = ("456","678","567") printDictionary(dictionaryTest) Output code Key 1 123 234 345 Key 2 456 567 678

try this 尝试这个

def printDictionary(dictionaryParm):

    for x in dictionaryParm:
        header = []
        header.append(x)

        #print header

        value=list(dictionaryParm.get(x))
        print value
        output = header + value
        for item in output:
            print item

dictionaryTest = dict()
dictionaryTest["Key 1"] = ("123","234","345")
dictionaryTest["Key 2"] = ("456","567","678")

printDictionary(dictionaryTest)

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

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