检查另一个字典中是否存在python字典中值列表中的值

时间:2017-11-15 15:31:09

标签: python python-3.x csv dictionary

我编写了一个python脚本来验证报告模板。有一个主模板,其中包含所有可能的报告及其所有可能的字段。然后有一个模板csv,其中包含一些报告。为简单起见,我们可以说看起来像这样;

模板csv:

OutputName, col1, col2, col3, col4, col5 PersonReport, name, surname, street, age, id TransactionReport, f1, f2, f3, f4, f5

掌握csv:

AccountReport

因此,在此示例中,PersonReport甚至不存在于主文件中,dob包含一个字段TransactionReport,该字段不是有效的,因为它不是&#39 ;在主人。唯一有效的报告是OutputName

所以我的想法是以字典的形式阅读这些csvs,其中 import pandas as pd masterDf = pd.read_csv('master.csv') master = masterDf.set_index('OutputName').T.to_dict('list') templateDf = pd.read_csv('template.csv') template = templateDf.set_index('OutputName').T.to_dict('list') 为关键字段,字段名称为值。

template = {' PersonReport': [' name', ' surname', ' age', ' dob', ' id'], ' AccountReport': [' f1', ' f2', ' f3', ' f4', ' f5 '], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

词典看起来像;

master = {' PersonReport': [' name', ' surname', ' street', ' age', ' id'], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}

errorCount = 0 for key, value in template.items(): if key not in master: print("{} is an invalid report".format(key)) errorCount += 1 if key in master: for fields in template.values(): for field in fields: for cols in master.values(): if field not in cols: print("{} is an invalid field in {} report".format(field, key)) errorCount += 1

现在我想首先匹配按键,找出哪些按键不存在于主指令中。在找到匹配的密钥之后,我希望检查字典中的值是否有效,方法是检查它们是否存在于主密码的值中。

所以我试试:

name is an invalid field in  PersonReport report
 surname is an invalid field in  PersonReport report
 age is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 dob is an invalid field in  PersonReport report
 id is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f5  is an invalid field in  PersonReport report
 f1 is an invalid field in  PersonReport report
 f2 is an invalid field in  PersonReport report
 f3 is an invalid field in  PersonReport report
 f4 is an invalid field in  PersonReport report
 f5 is an invalid field in  PersonReport report
 AccountReport is an invalid report
 name is an invalid field in  TransactionReport report
 surname is an invalid field in  TransactionReport report
 age is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 dob is an invalid field in  TransactionReport report
 id is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f5  is an invalid field in  TransactionReport report
 f1 is an invalid field in  TransactionReport report
 f2 is an invalid field in  TransactionReport report
 f3 is an invalid field in  TransactionReport report
 f4 is an invalid field in  TransactionReport report
 f5 is an invalid field in  TransactionReport report

然而我得到的输出是错误的。我明白了:

AccountReport is an invalid report
dob is an invalid field in PersonReport report

我的预期输出将是:

    package com.example.gilad.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private List<Notes> notesList = new ArrayList<>();
    private static final int REQUEST_CODE = 1001;
    final NoteAdapter adapter = new NoteAdapter(this);
    private View mRemoveAllButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final RecyclerView recyclerView = findViewById(R.id.rv_recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        Button addNoteButton = findViewById(R.id.button_main_addNote);
        mRemoveAllButton = findViewById(R.id.button_main_deleteAll);
        addNoteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, NoteEdit.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });


        mRemoveAllButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.removeAll();
                mRemoveAllButton.setVisibility(View.GONE);
            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE &&
                resultCode == RESULT_OK &&
                data != null) {
            String noteTitle = data.getStringExtra(NoteEdit.Result_Key_Title);
            String noteDescription = data.getStringExtra(NoteEdit.Result_Key_Description);
            Notes notes = new Notes();
            notes.setNoteTitle(noteTitle);
            notes.setNoteDescription(noteDescription);
            adapter.addNote(notes);
            final int adapterCount = adapter.getItemCount();
            if (adapterCount == 1){
                mRemoveAllButton.setVisibility(View.VISIBLE);
            }
        }
    }}

感谢任何帮助 谢谢 请使用python 3.6

3 个答案:

答案 0 :(得分:1)

你可以试试这个:

template = {' PersonReport': [' name', ' surname', ' age', ' dob', ' id'], ' AccountReport': [' f1', ' f2', ' f3', ' f4', ' f5 '], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}
master = {' PersonReport': [' name', ' surname', ' street', ' age', ' id'], ' TransactionReport': [' f1', ' f2', ' f3', ' f4', ' f5']}
invalid_names = ["{} in dict".format(i) if i in master else "{} not in dict".format(i) for i in template]
invalid_values = filter(lambda x:x, [["{} is an invalid value".format(c) for c in b if c not in master[a]] for a, b in template.items() if a in master])
print(invalid_names)
print(invalid_values)

输出:

[' TransactionReport in dict', ' PersonReport in dict', ' AccountReport not in dict']
[[' dob is an invalid value']]

答案 1 :(得分:1)

您的代码有几处错误导致您检查每个字段。使用continue并且仅迭代正确的密钥解决了这个问题。 这是一个固定的代码片段:

for key in template.keys():
    if key not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
        continue # Continue to next key
    cols = master[key] # Get the correct column names from the current key
    errorFlag = False
    for field in template[key]:
        if field not in cols:
            print("{} is an invalid field in {} report".format(field, key)) 
            errorCount += 1
            errorFlag = True # You can break here if you wish not to keep incrementing the errorCount.

    if not errorFlag: # We did not find any bad column
        print("Success finding valid {} report in master".format(key))

输出:

 dob is an invalid field in  PersonReport report
 AccountReport is an invalid report
Success finding valid  TransactionReport report in master

答案 2 :(得分:1)

我保持简单并遵循您的惯例:

errorCount = 0

for key in template.keys():
    if key not in master:
        print("{} is an invalid report".format(key))
        errorCount += 1
    else:
        if template[key] != master[key]:
            fields = [f for f in template[key] if f not in master[key]]
            for f in fields:
                print("{} is an invalid field in {} report".format(f, key))
                errorCount += 1

从控制台:

AccountReport is an invalid report
dob is an invalid field in  PersonReport report