如何将带有列表值的字典转换为表

时间:2016-11-30 09:48:17

标签: python json list dictionary

我有字典:

{"A": [1,2,3], "B": [5,7,9], "C":[12,5,6]}

我希望它采用以下格式的表格:

A  |   1
A  |   2
A  |   3
B  |   5
B  |   7
.  |   .
.  |   .
C  |   6

4 个答案:

答案 0 :(得分:1)

也许你需要数据展示。可能有不同的方法 此

这是一个简单的python代码,看看它是否适合你需要。

def dict_list_value_to_table(dict_with_list):
    """
    Function coverts a dictionary of list as it's 
    values to table format.
    >>> {"A": [1,2,3], "B": [5,7,9], "C":[12,5,6]}
    A  |  1
    A  |  2
    A  |  3
    B  |  5
    B  |  7
    B  |  9
    C  |  12
    C  |  5
    C  |  6

    """

    # Sorts the records orderly.
    for key in sorted(dict_with_list):
        for values in dict_with_list.get(key):
            print key, " | ", values 

    # Commented below does not sort.
    # But does the same.

    #for key, value in dict_with_list.items():
    #    for v in value:
    #        print key, "|",v  
    #        
    return 

if __name__=="__main__":
    arg = {"A": [1,2,3], "B": [5,7,9], "C":[12,5,6]}
    dict_list_value_to_table(arg)

如果你想要一些先进的东西,请按照评论中的建议寻找

numpy pandas 以及其他高级python数据结构。

答案 1 :(得分:1)

d = {"A": [1,2,3], "B": [5,7,9], "C":[12,5,6]}
# make dictionary to list
l = []
for key, value in d.iteritems():
    temp = (key, value)
    l.append(temp)
# sort list
l = sorted(l, key = lambda x: x[0])
# finally!
for key, lists in l:
    for item in lists:
        print( "{}|{}".format(key, item) )

答案 2 :(得分:1)

如果您想要添加确切顺序的元素,请使用OrderedDict

# tested in python2.7, 3.5

from collections import OrderedDict
data = {"A": [1,2,3], "B": [5,7,9], "C": [12,5,6]}
# expecting alpha order "A"
sorted_data = OrderedDict(sorted(data.items(), key=lambda t: ord(t[0])))

for key, value in sorted_data.items():
    for le in value:
        print("{}|{}".format(key, le))

答案 3 :(得分:0)

dict = {"A": [1,2,3], "B": [5,7,9], "C":[12,5,6]}
for k,value in sorted(dict.items()):
  if isinstance(value, list):
     for v in sorted(value):
     # key and value are sorted
     print ("{0} | {1}".format(k, v))

输出:

A | 1
A | 2
A | 3
B | 5
B | 7
B | 9
C | 5
C | 6
C | 12