使用字典查找冲突并设置Python

时间:2017-05-30 01:17:58

标签: python python-3.x dictionary set

我正试图弄清楚如何发生冲突

nbr_dict  = {'key1': {1, 2, 3}, 'key2': {4, 5, 6}, 'key3': {1,5}}

我希望它看起来像

Clashes?: key1
key1 and key2: None
key1 and key3: 1

Clashes?: key2
key2 and key1: None
key2 and key3: 5

Clashes?: key3
key3 and key1: 1
key3 and key2: 5

以下是我设法获得的代码示例:

def main():
    nbr_dict  = {'key1': {1, 2, 3}, 'key2': {4, 5, 6}, 'key3': {1,5}}
    clashes = input('Clashes?: ')
    for key in sorted(nbr_dict):
        if key != clashes:
            print('{} and {}'.format(clashes, key))
            #I'm pretty sure all the arithmetic goes here#

main()

假设用户提供的所有输入均有效

2 个答案:

答案 0 :(得分:3)

你需要交集。

for key, value in nbr_dict.items():
    if key != clashes:
        diff = nbr_dict[clashes] & value
            if len(diff):
                 print (key, diff)   # I leave you to figure out the formatting here

正如问题评论中已经指出的那样,您不需要对字典进行排序。但是,正如MSeifert所指出的那样,如果显示顺序很重要,您可能仍需要进行排序。

答案 1 :(得分:1)

为什么不使用set交集,您的数据已经在集合中:

def main():
    nbr_dict = {'key1': {1, 2, 3}, 'key2': {4, 5, 6}, 'key3': {1, 5}}
    clashes = input('Clashes?: ')
    if clashes in nbr_dict:
        target = nbr_dict[clashes]
        for k, v in nbr_dict.items():
            if k != clashes:
                # for raw data: `target & v`, the rest is just to match your desired output
                clash_values = [str(i) for i in target & v]
                print("{} and {}: {}".format(clashes, k, ", ".join(clash_values) or None))
    else:
        print("No such key: {}".format(clashes))

main()

Clashes?: key1
key1 and key3: 1
key1 and key2: None

Clashes?: key2
key2 and key3: 5
key2 and key1: None

Clashes?: key3
key3 and key2: 5
key3 and key1: 1

Clashes?: key4
No such key: key4

编辑:如果您需要排序版本,它大致相同:

def main():
    nbr_dict = {'key1': {1, 2, 3}, 'key2': {4, 5, 6}, 'key3': {1, 5}}
    sorted_keys = sorted(nbr_dict.keys())  # lets get a nice list of sorted keys
    clashes = input('Clashes?: ')  # user input
    if clashes in nbr_dict:  # simple validation
        target = nbr_dict[clashes]  # this is our user selected set
        for k in sorted_keys:  # lets loop through our sorted keys
            if k != clashes:  # don't compare with the user selected key
                v = nbr_dict[k]  # this is our compare set
                # the same boilerplate from now on...
                clash_values = [str(i) for i in target & v]
                print("{} and {}: {}".format(clashes, k, ", ".join(clash_values) or None))
    else:
        print("No such key: {}".format(clashes))

如果集合交叉点中的元素也应按照排序方式打印,则可以进一步对clash_values进行排序。