创建dict结合其他两个dicts

时间:2017-10-21 19:16:53

标签: python dictionary

从另外两个dicts(非常大的和小的)创建一个dict的最佳方法是什么?

我们有:

    big_dict = {
    'key1':325,
    'key2':326,
    'key3':327,
    ...
    }

    small_dict = {
    325:0.698,
    326:0.684,
    327:0.668
    }

需要在small_dict中获取数据的dict,但我们应该使用big_dict中的键:

    comb_dict = {
    'key1':0.698,
    'key2':0.684,
    'key3':0.668
    }

4 个答案:

答案 0 :(得分:2)

以下代码适用于所有情况(示例显示在驱动程序值中),采用更EAFP方法。

>>> d = {}
>>> for key,val in big_dict.items(): 
        try: 
            d[key] = small_dict[val] 
        except KeyError: 
            continue

=> {'key1': 0.698, 'key2': 0.684, 'key3': 0.668}

#driver values:

IN : big_dict = {
        'key1':325,
        'key2':326,
        'key3':327,
        'key4':330        #note that small_dict[330] will give KeyError
     }

IN : small_dict = {
          325:0.698,
          326:0.684,
          327:0.668
      }

或者,使用Dictionary Comprehension

>>> {key:small_dict[val] for key,val in big_dict.items() if val in small_dict}

=> {'key1': 0.698, 'key2': 0.684, 'key3': 0.668}

答案 1 :(得分:1)

您可以使用词典理解:

private int seconds = 0;
    private boolean running = false;
    private boolean wasRunning = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stop_watch_revision);
        if(savedInstanceState!=null){

            seconds = savedInstanceState.getInt("seconds");
            running = savedInstanceState.getBoolean("running");
            wasRunning = savedInstanceState.getBoolean("wasRunning");

        }
        runningTime();
    }
    public void onSaveInstanceState(Bundle sv){

        sv.putInt("seconds",seconds);
        sv.putBoolean("running",running);
        sv.putBoolean("wasRunning",wasRunning);

    }

    public void onStop(){

        super.onStop();
        wasRunning = running;
        running = false ;


    }


    public void onStart() {

        super.onStart();
        if (wasRunning) {
            running = true;
        }
    }
  /*Removing the onStart() method and adding the onRestart() method gives the same result*/ 

    public void onRestart() {

        super.onRestart();
        if (wasRunning) {
            running = true;
        }
    }

    public void runningTime() {

        final TextView txt_time = (TextView) findViewById(R.id.txt_time);
        Handler handler = new Handler();
        handler.post(new Runnable() {

            public void run() {

                int hours = seconds / 3600;
                int mins = (seconds % 3600) / 60;
                int secs = seconds % 60;
                String time = String.format("%d:%02d:%02d", hours, mins, secs);
                txt_time.setText(time);

                if (running) {


                    seconds++;
                }

                new Handler().postDelayed(this, 1000);
            }


        });

    }

如果comb_dict = {k: small_dict[v] for k, v in big_dict.iteritems()} 可能包含big_dict中不是键的值,您可以忽略它们:

small_dict

或使用原始值:

comb_dict = {k: small_dict[v] for k, v in big_dict.iteritems() if v in small_dict}

(在Python3中使用{k: (small_dict[v] if v in small_dict else v) for k, v in big_dict.iteritems()}

答案 2 :(得分:1)

如果big_dict中的值可能不会作为small_dict中的键出现,则可以使用:

combined_dict = {}
for big_key, small_key in big_dict.items():
    combined_dict[big_key] = small_dict.get(small_key)

或者您可能希望使用不同的默认值,而不是:

    combined_dict[big_key] = small_dict.get(small_key, default='XXX')

或者您可能需要提出KeyError来表明您的数据存在问题:

    combined_dict[big_key] = small_dict[small_key]

或者您可能想要跳过丢失的密钥:

    if small_key in small_dict:
        combined_dict[big_key] = small_dict[small_key]

答案 3 :(得分:0)

keys = small_dict.keys()
combined_dict = {k:small_dict[v] for k,v in big_dict.items() if v in keys}
>>> combined_dict
{'key3': 0.668, 'key2': 0.684, 'key1': 0.698}