python - 如何比较3个字典并返回键和值

标签 python python-2.7

我想比较 3 个字典,找出所有 3 个字典中哪些变量及其关联值相同,哪些变量及其值不同。

这 3 个字典的键和值是通过读取 3 个文本文件找到的,所以我不知道字典中哪个变量和值会排在前面。

假设我有如下 3 个词典:

d1 = {'var1': ' ', 'var2': 'high', 'var3': '50'}
d2 = {'var2': 'low', 'var3': '50', 'var4': '80'}
d3 = {'var2': 'high', 'var3': '50', 'var4': '100'}

我的最终结果是将其保存到文本文件中,然后在 Excel 中打开它,结果将显示在列中,然后我应该看到类似以下内容的内容:

Common Variables
var3 50 50 50

另一个文件将显示不同的变量

Different Variables
var1
var2 high low high
var4      80  100

我能想到的是得到类似的东西:

common_var_and_val = {'var3': '50'}
diff_var_and_val = {'var1': (' ',' ',' '), 'var2': ('high', 'low', 'high'), 'var4': (' ','80''100')}

请注意,diff_var_and_val 会告诉我 d1、d2 和 d3 中变量的值是多少(如果变量不存在,则该值将为空格),因此值的顺序很重要(高、低) , high = d1, d2, d3) 中的值。该值可以是字符串、整数或任何内容。我正在使用Python 2.7

我的问题:

a) how to get common_var_and_val and diff_var_and_val? is there a better way to do what I want to do?

b) what should I do so that if I open the output file in Excel it will display exactly like what I mentioned above.

最佳答案

这是第一个问题的答案(这是一个更一般的答案 - 该函数可以接收任意数量的字典)。最后有一个如何使用代码的示例。

基本上,该函数检查每个键是否在所有字典中,如果是,则该值在将其存储在“公共(public)”字典中的所有字典中都相等,如果不是,则该函数检查该键是否在所有字典 - 如果键不在字典中,则值为 '' (否则它是真正的值...)

def f(*args):
    if args == []: return {},{}
    all_keys = set([])
    for dictionary in args:
        for keys in dictionary:
            all_keys.add(keys)
    common, diff = {},{}
    for k in all_keys:
        if check_equal_key(args,k):
            common[k] = [dictionary[k] for dictionary in args]
        else:
            diff[k]= []
            for dictionary in args:
                diff[k].append(dictionary[k] if k in dictionary else '')
    return common,diff

def check_equal_key(dict_list, k):
    '''this function check if a key is in all the dicts and if yes check if the value in equal in all the dictionaries'''
    if False in [True if k in dictionary else False for dictionary in dict_list]: return False
    prim_value = dict_list[0][k]
    for dictionary in dict_list[1:]:
        if prim_value != dictionary[k]: return False
    return True

a = {1:123,2:1,65:'as'}
b = {1:123,2:2,65:'asa'}
c = {1:123,2:1,67:'as'}
common,diff = f(a,b,c)
print common,'\r\n',diff

对于第二个问题:(主要函数是“f2”,它接收 2 个字典(最后一个答案的输出)并将其写入名为 Expenses01.xlsx 的 Excel 文件。注意,您将需要 xlsxwriter 模块(已安装)在 python 中):

import xlsxwriter
def f2(common,diff):
    # Create a workbook and add a worksheet.
    workbook = xlsxwriter.Workbook('Expenses01.xlsx')
    worksheet = workbook.add_worksheet()

    # Start from the first cell. Rows and columns are zero indexed.
    row = 0
    col = 0

    worksheet.write(row,col,'common values:')
    row += 1
    row = write_dict(common,worksheet,row)   #write the 'common' dict

    worksheet.write(row, col, 'different values:')
    row += 1
    row = write_dict(diff,worksheet,row)     #write the diff' dict

    workbook.close()

def write_dict(dictionary,worksheet,row):
    '''this function write the dict in the excel file
    each key in a different row each value separated by a column, the function return the current row'''
    col = 0
    for k in dictionary:
        worksheet.write(row, col, k)
        for value in dictionary[k]:
            col += 1
            worksheet.write(row, col, value)
        col = 0
        row += 1
    return row

common = {1: [123, 123, 123]}
diff = {65: ['as', 'asa', ''], 2: [1, 2, 1], 67: ['', '', 'as']}
f2(common,diff)

基本代码取自here你也许应该检查一下。

编辑:当您不想使用任何模块时,您可以使用以下代码来执行以下操作:它创建一个新的txt文件,当用excel打开时,excel将显示数据就像你想要的那样。为此,每一行用“\n”分隔,每列用制表符“\t”分隔,每个值都在双引号内(例如“”),最后有一个如何使用的示例。

(如果你问我,我会推荐使用该库......)

def create_excel_txt_file_data(common,diff,file_path_and_name):
    '''create the data to be written in the txt file in excel format'''
    file_data = ''
    file_data+='"{}"\n'.format('common values:')   #file data will be equal "common values:"\n (with th quots)
    file_data+=write_dict(common)
    file_data += '"{}"\n'.format('different values:')
    file_data += write_dict(diff)
    with open(file_path_and_name, 'w') as f:
        f.write(file_data)

def write_dict(dictionary):
    '''this function write the dict
    each key in a different row each value separated by a column'''
    data = ''
    for k in dictionary:
        data += '"{}"'.format(str(k))
        for value in dictionary[k]:
            data += '\t"{}"'.format(str(value))   #between each colomn is a tab (\t)
        data += '\n'
    return data

common = {1: [123, 123, 123]}
diff = {65: ['as', 'asa', ''], 2: [1, 2, 1], 67: ['', '', 'as']}
create_excel_txt_file_data(common, diff, 'Book1.txt')

希望我能有所帮助。

关于python - 如何比较3个字典并返回键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37906452/

相关文章:

python:在后台运行命令

python - celery :消费者:无法连接到 amqp://guest:**@127.0.0.1:5672//:[Errno 92] 协议(protocol)不可用

python - 字符串操作 - 在参数列表之间串接 '&'

Python:如何处理回归 Q-Q 图中的异常值?

python-2.7 - 模块 chembl_webresource_client.new_client 失败,因为 python 2.7.9 下的 urllib3 中的 ssl 损坏

python - Homebrew python 公式 pip 安装

python - Python 2 中的 TicTacToe 项目 : I am trying to avoid using global variables and return variables instead

python - 如何忽略矩阵乘法中的零?

python - 在 url 错误中搜索单词

python - 比较相同索引python中列表中的项目