Home > database >  How can I handle only the first part of my value list of a dictionary in Python?
How can I handle only the first part of my value list of a dictionary in Python?

Time:03-28

I have a dictionary which has a list of values and I want to use only the first value of each pair before the first comma. Is that possible? This is the format of my dictionary values

If you came across anything similar please write it down

CodePudding user response:

if you have a dictionary d, then use

d.keys() to return the keys of your dictionary, which is the first item in each key value pair that makes up a dictionary

CodePudding user response:

The output you expect is unclear. If you want a dictionary in which you only keep the first item of the sublist, use a dictionary comprehension:

Assuming dic1 the input.

dic2 = {k:v[0][0] for k,v in dic1.items()}

CodePudding user response:

It's definitely possible.

I'll assume for now that by: "I want to use only the first value of each pair", you mean you want to extract the first value of each pair from the dict.

Now, the answer to that depends slightly on what you ment by "pair".
If you ment the items you can get out of the items method on the dict, then the simplest way to get the first element of each of these pairs would be the keys method, also directly on the dict. In code:

def get_fist_from_pair(d: dict): 
  return d.keys()

In the image you provided, the values stored in the dict are lists of each length 1, filled with another list. If this inner list is what you ment by "pairs", the code would be slightly different:

def get_fist_from_pair(d: dict):
  return [v[0][0] for v in dict.values()]

This code looks at each value and extracts the first element of the inner list.
In case that this interpretation of pair is correct, but you also want to associate the key with that element in a new dict, the code for it would be:

def get_first_from_pair(d: dict): 
  return {key: d[key][0][0] for key in d}
  • Related