如何从dict获取值列表?

时间:2013-04-26 03:25:57

标签: python list dictionary

如何在Python中获取dict中的值列表?

在Java中,将Map的值作为List获取就像执行list = map.values();一样简单。我想知道在Python中是否有一种类似的简单方法来从字典中获取值列表。

5 个答案:

答案 0 :(得分:292)

是的Python 2中完全相同:

d.values()

Python 3中(其中dict.values会返回字典值的view):

list(d.values())

答案 1 :(得分:3)

按照下面的示例-

songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]

print("====================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')

playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')

# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))

答案 2 :(得分:2)

您可以使用* operator解压缩dict_values:

>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']

或列表对象

>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']

答案 3 :(得分:2)

考虑到Python3,什么更快?

public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState?) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check that the activity is using the layout version with
    // the fragment_container FrameLayout
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create a new Fragment to be placed in the activity layout
        HeadlinesFragment firstFragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from an
        // Intent, pass the Intent's extras to the fragment as arguments
        firstFragment.setArguments(getIntent().getExtras());

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();
    }
}
}
small_ds = {x: str(x+42) for x in range(10)}
small_di = {x: int(x+42) for x in range(10)}

print('Small Dict(str)')
%timeit [*small_ds.values()]
%timeit list(small_ds.values())

print('Small Dict(int)')
%timeit [*small_di.values()]
%timeit list(small_di.values())

big_ds = {x: str(x+42) for x in range(1000000)}
big_di = {x: int(x+42) for x in range(1000000)}

print('Big Dict(str)')
%timeit [*big_ds.values()]
%timeit list(big_ds.values())

print('Big Dict(int)')
%timeit [*big_di.values()]
%timeit list(big_di.values())

结果

  1. 对于重要的大型词典,Small Dict(str) 284 ns ± 50.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 401 ns ± 53 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) Small Dict(int) 308 ns ± 79.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 428 ns ± 62.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) Big Dict(str) 29.5 ms ± 13.8 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) 19.8 ms ± 1.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) Big Dict(int) 22.3 ms ± 1.4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) 21.2 ms ± 1.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) 更快
  2. 对于小型词典,list()更快

答案 4 :(得分:-1)

out: dict_values([{1:a, 2:b}])

in:  str(dict.values())[14:-3]    
out: 1:a, 2:b

纯粹出于视觉目的。不会产生有用的产品...仅当您希望将长字典以段落类型形式打印时有用。