Python: While Statement = Statement Print associated Values

半世苍凉 提交于 2020-02-05 09:10:18

问题


In Python I currently have a Dictionary with a composite Key. In this dictionary there are multiple occurences of these keys. (The keys are comma-separated):

(A,B), (A,C), (A,B), (A,D), (C,A), (A,B), (C,A), (C,B), (C,B)

I already have something that totals the unique occurrences and counts the duplicates which gives me a print-out similar to this:

(A,B) with a count of 4, (A,C) with a count of 2, (B,C) with a count of 6, etc.

I would like to know how to code a loop that would give me the following:

Print out the first occurance of the first part of the key and its associtated values and counts.

Name: A:

Type Count

B     4
C     2

Total  6

Name: B:

Type Count
A    3
B    2
C    3
Total 8

I know I need to create a loop where the first statement = the first statement and do the following, but have no real idea how to approach/code this.


回答1:


Here's a slightly slow algorithm that'll get it done:

def convert(myDict):
    keys = myDict.keys()
    answer = collections.defaultdict(dict)
    for key in keys:
        for k in [k for k in keys if k.startswith(key[0])]:
            answer[key[0]][k[1]] = myDict[k]
    return answer

Ultimately, I think what you're after is a trie




回答2:


Its a little misleading to say that your dictionary has multiple values for a given key. Python doesn't allow that. Instead, what you have are keys that are tuples. You want to unpack those tuples and rebuild a nested dictionary.

Here's how I'd do it:

import collections

# rebuild data structure
nested = collections.defaultdict(dict)
for k, v in myDict.items():
    k1, k2 = k                # unpack key tuple
    nested[k1][k2] = v

# print out data in the desired format (with totals)
for k1, inner in nested.items():
    print("%s\tType\tCount" % k1)
    total = 0
    for k2, v in innner.items():
        print("\t%s\t%d" % (k2, v))
        total += v
    print("\tTotal\t%d" % total)


来源:https://stackoverflow.com/questions/12905602/python-while-statement-statement-print-associated-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!