采摘某些字典集

时间:2016-03-05 18:58:54

标签: python python-2.7 dictionary

我试图在任何地方找到解决方案,但我找不到解决这个问题的方法。假设我在列表中有多个词典:

[
    {"Type": "A", "Name": "Sam"},
    {"Type": "A", "Name": "Apple"},
    {"Type": "B", "Name": "Sam"},
    {"Type": "C", "Name": "Apple"},
    {"Type": "C"}
]

我需要的是具有'Type' == 'A'的词典。

我想要的结果是:

[{"Type": "A", "Name": "Sam"}, {"Type": "A", "Name": "Apple"}]

有什么办法可以实现这个目标吗?任何帮助或任何解决这个问题的方向都会很棒。

4 个答案:

答案 0 :(得分:2)

浏览您的列表并使用Type A的所有词典:

>>> data = [{"Type": "A", "Name": "Sam"},{"Type":"A", "Name":"Apple"},{"Type": "B", "Name": "Sam"},{"Type":"C", "Name":"Apple"},{"Type":"C"}]
>>> [d for d in data if d.get('Type') == 'A']
[{'Name': 'Sam', 'Type': 'A'}, {'Name': 'Apple', 'Type': 'A'}]

使用dict.get()确保它适用于没有密钥Type

的字符串
data = [{"Type": "A", "Name": "Sam"},
        {"Type":"A", "Name":"Apple"},
        {"Type": "B", "Name": "Sam"},
        {"Type":"C", "Name":"Apple"},
        {"Type":"C"},
        {}]
>>> [d for d in data if d.get('Type') == 'A']
[{'Name': 'Sam', 'Type': 'A'}, {'Name': 'Apple', 'Type': 'A'}]

,因为:

  

get(key[, default])

     

如果key在字典中,则返回key的值,否则返回default。如果未给出default,则默认为None,因此此方法永远不会引发KeyError。

答案 1 :(得分:0)

public static class ListMenuRowViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    protected NetworkImageView thumbnail;
    protected TextView itemname;
    protected TextView price;
    protected TextView itemtype;
    protected TextView quantity;
    protected ImageView add;
    protected ImageView sub;
    protected ImageView imageView;
    protected CardView item_layout;

    public ListMenuRowViewHolder(View itemView) {
        super(itemView);

        this.thumbnail = (NetworkImageView) itemView.findViewById(R.id.recom);
        this.imageView = (ImageView) itemView.findViewById(R.id.categ);
        this.itemname = (TextView) itemView.findViewById(R.id.itemvalue);
        this.add = (ImageView) itemView.findViewById(R.id.add);
        this.sub = (ImageView) itemView.findViewById(R.id.sub);
        this.price = (TextView) itemView.findViewById(R.id.price);
        this.quantity = (TextView) itemView.findViewById(R.id.quantity);

        this.add.setOnClickListener(this);
        this.sub.setOnClickListener(this);
        //Do this for each view
    }

    @Override
    public void onClick(View v) {
        Log.e("myname", "rohit");
        ItemscardClickListener.onClick(v, getAdapterPosition());
    }
}

答案 2 :(得分:0)

[d for d in d_list if d.get('Type') == 'A']

答案 3 :(得分:0)

这几乎绝对不是最狡猾的方式,但如果你需要快速而肮脏的解决方案,我相信它有效。

 def filterDictionaries(dictionaries, type):
      filteredDicts = []
      for dict in dictionaries:
          if 'Type' in dict:
             if dict['Type] == type:
                filteredDicts += dict
      return filteredDicts