简体   繁体   中英

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_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)?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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