Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extact elements from dictionary of lists efficiently?

Here is my initial dictionary:

dic = {'key1': [2,3],
       'key2': [5,1],
       'key3': [6,8]}

NB: I am using simple numbers 2,3, etc. for the purpose of the example (list of dfs on my side).

For each key, I would like to extract the first element and obtain the following result:

dic2 = {'key1': 2,
        'key2': 5,
        'key3': 6}

Is it possible to do it without going for a slow for loop ? The dictionary is quite large...

Many thanks in advance for your help.

like image 530
plonfat Avatar asked Dec 07 '22 09:12

plonfat


1 Answers

If you expect to access only a few keys of the dictionary after this conversion, you could write a wrapper; something like:

class ViewFirst:
  def __init__(self, original):
    self.original = original
  def __getitem__(self, key):
    return self.original[key][0]

Another option is to base it on defaultdict; that will let you do things like assigning new values into the dictionary (new or existing keys) while still retrieving other values from the original dictionary:

class DictFromFirsts(collections.defaultdict):
  def __init__(self, original):
    self.original = original
  def __missing__(self, key):
    return self.original[key][0]

Edit: Per the discussion in the comments, this is rather a special-purpose approach, for a specific scenario. For general-purpose use, prefer one of the approaches in the other answers, such as U12-Forward's dict comprehension {k: v[0] for k, v in dic.items()}; it's clear and straightforward, which is usually the more important concern.

like image 139
Jiří Baum Avatar answered Jan 25 '23 23:01

Jiří Baum