处理词典列表

时间:2018-08-23 10:53:05

标签: python json list dictionary data-manipulation

我已成功从网络上导入了这个json文件,如下所示:

[{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"},{"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"},
等等...

我想提取键moid_au的值,以后将moid_auh_mag的键值进行比较。

此方法有效:print(data[1]['moid_au']),但是如果我尝试询问列表中所有不会的元素,我会尝试:print(data[:]['moid_au'])

我尝试了迭代器和一个lambda函数,但仍然无法使用,主要是因为我是数据处理方面的新手。当我只有一本字典而不是一本字典时,它可以工作。

预先感谢其他提示。一些链接令人困惑。

4 个答案:

答案 0 :(得分:2)

听起来您使用lambda的声音是错误的,因为您也需要map

c = [{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"},{"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"}]

list(map(lambda rec: rec.get('moid_au'), c))
['0.035', '0.028']

每个lambda都会从列表中获取一条记录,然后将函数映射到该记录。

答案 1 :(得分:2)

使用 @Override public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) { final MainInterestModel mainInterestModel = mainInterestModels.get(position); holder.tvName.setText(mainInterestModel.getName()); holder.ivMainInterest.setImageResource(mainInterestModel.getImage()); // here isSelected is always false because in activity infalting adpter with arraylist, i want to setSeletced by hash object boolean isSelected = mainInterestModel.isSelected(); if (isSelected) { holder.ivMainInterest.setImageResource(R.drawable.bath_selector); Log.e("Is Item selected ::", "" + mainInterestModel.getId()); } else { holder.ivMainInterest.setImageResource(R.drawable.ic_bath); Log.e("Is Item deselected ::", "" + mainInterestModel.getId()); } holder.ivMainInterest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean selection = mainInterestModel.isSelected(); if (selection) { holder.ivMainInterest.setImageResource(R.drawable.ic_bath); mainInterestModel.setSelected(false); mainIntrestHash.remove(mainInterestModel.getId()); Log.e("After Remove SIZE:---", "" + mainIntrestHash.size()); } else { mainInterestModel.setSelected(true); holder.ivMainInterest.setImageResource(R.drawable.bath_selector); mainIntrestHash.put(mainInterestModel.getId(), mainInterestModel); Log.e("After Adding SIZE:---", "" + mainIntrestHash.size()); } } }); } 等于print(data[:]['moid_au']),您会发现它不起作用,因为print(data['moid_au'])没有名为data的密钥。

尝试使用循环:

'moid_au'

答案 2 :(得分:2)

使用您的方法遍历整个数组以获取键的所有实例,此方法可能对您有用

a = [data[i]['moid_au']for i in range(len(data))]
print(a)

答案 3 :(得分:1)

您想用哪种确切的方式进行比较?

以这种方式获取值是否有用?

list_of_dicts = [{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"}, {"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"}]
mod_au_values = [d["moid_au"] for d in list_of_dicts]
h_mag_values = [d["h_mag"] for d in list_of_dicts]