简体   繁体   English

将函数应用于python中dict的值

[英]applying a function over the values of dict in python

I have dictionary something like this, where the values are a list by itself. 我有这样的字典,其中的值本身就是一个列表。

import random
dict_size = 10
my_dict = dict(zip(np.random.randint(1000000,size=dict_size ), 
               map(lambda x: [random.randrange(10000)],range(dict_size ))))

my_dict
#
 {187898: [1209],
  189434: [8294],
  201447: [1258],
  317844: [7760],
  330804: [2305],
  679881: [1738],
  754108: [8503],
  758119: [712],
  845631: [2372],
  870357: [340]}

I want to get the values of the dictionary in certain order my_key_order (I created an example of the order but I have the actual order with me) as well as flattening it. 我想按一定的顺序my_key_order字典的值my_key_order (我创建了该顺序的一个示例,但是我已经有了实际的顺序),并且将其展平。

my_key_order = [*my_dict]

Expected output: 预期产量:

[7760, 340, 2305, 1258, 1738, 8294, 712, 8503, 1209, 2372]

Current approach: 当前方法:

[*map(lambda x:my_dict[x][0], my_key_order)] 

Is there any other more elegant way to do faster (may be without using lambda)? 还有其他更优雅的方法来更快地执行操作(可能不使用lambda)吗?

I think a list comprehension looks a bit cleaner and simpler: 我认为列表理解看起来更简洁一些:

[my_dict[x][0] for x in my_key_order]

this just loops through your order and gets that item from the dictionary, unpacking it using indexing 这只会遍历您的订单并从字典中获取该项目,并使用索引将其拆包

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM