按属性对字典项进行分组

时间:2016-09-15 10:36:29

标签: python dictionary

我正在尝试按特定键将字词中的项目分组,让我们说我们有以下字典:

[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, {'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}]

我希望按type对这些项目进行分组。根据{{​​3}},可以使用defaultdict()来完成,因为它不会引发KeyError,如下所示:

grouped = defaultdict()
for item in items:
    grouped[item.type].append(item)

但是,我实际上得到的是KeyError

那有什么不对?我看到的所有信息defaultdict()都应该创建一个空列表,如果它不存在,并插入元素。

我正在使用Python 2.7。

3 个答案:

答案 0 :(得分:2)

使用defaultdict(list),而不是defaultdict()。阅读defaultdict的文档以了解更多信息。

另外,你不能使用some_dict.a_key(在你的情况下:.type) - 你必须使用some_dict [&#39; a_key&#39;](在你的情况下[&#39;类型&#39;])< / p>

答案 1 :(得分:0)

您还可以使用普通字典及其{{​​3}}方法:

{'plant' : [{'type': 'plant', 'name': 'orange tree'}], 
 'animal': [{'type': 'animal', 'name': 'rabbit'}, 
            {'type': 'animal', 'name': 'cow'}, 
            {'type': 'animal', 'name': 'coyote'}]}

结果就是这个(格式很好):

   @RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class HearthBeatUITest {

    private final int MILISECONDS_TIMEOUT = 700;

    @Rule
    public ActivityTestRule<IntroActivity> mActivityRule = new ActivityTestRule<>(IntroActivity.class);
    @Rule
    public ActivityTestRule<LoginActivity> mLoginActivityRule = new ActivityTestRule<>(LoginActivity.class);

    @Test
    /**
     * Testing all the screens on the application if they are actually there
     */
    public void startTest() {
        Session.clear();
        Spoon.screenshot(mActivityRule.getActivity(), "initial_state");
        threadSleep(MILISECONDS_TIMEOUT);
        onView(withId(R.id.button_register)).check(matches(isDisplayed())).perform(click());
        threadSleep(MILISECONDS_TIMEOUT);
        Spoon.screenshot(mLoginActivityRule.getActivity(), "register_intro");
        onView(withId(R.id.register_with_email)).check(matches(isDisplayed())).perform(click());
        threadSleep(MILISECONDS_TIMEOUT);
        Spoon.screenshot(mLoginActivityRule.getActivity(), "register_detailed");
        onView(withId(R.id.image_left_button)).check(matches(isDisplayed())).perform(click());
        threadSleep(MILISECONDS_TIMEOUT);
        Spoon.screenshot(mLoginActivityRule.getActivity(), "register_intro");
        onView(withId(R.id.image_left_button)).check(matches(isDisplayed())).perform(click());
        threadSleep(MILISECONDS_TIMEOUT);
        Spoon.screenshot(mActivityRule.getActivity(), "initial_state");
        onView(withId(R.id.button_signin)).check(matches(isDisplayed())).perform(click());
        threadSleep(MILISECONDS_TIMEOUT);
        Spoon.screenshot(mLoginActivityRule.getActivity(), "login_intro");
        onView(withId(R.id.sign_in_emal)).check(matches(isDisplayed())).perform(click());
        threadSleep(MILISECONDS_TIMEOUT);
        Spoon.screenshot(mLoginActivityRule.getActivity(), "login_detailed");
    }

}

答案 2 :(得分:0)

from collections import defaultdict

animals=[{'type': 'animal', 'name': 'rabbit'}, {'type': 'animal', 'name': 'cow'}, 
{'type': 'plant', 'name': 'orange tree'}, {'type': 'animal', 'name': 'coyote'}]

animal_by_type = defaultdict(list)
for animal in animals:
    animal_by_type[animal['type']].append(animal['name'])
print animal_by_type