Home > OS >  get a dictionnary from a list with only 1 loop and no package import
get a dictionnary from a list with only 1 loop and no package import

Time:10-15

I have this list:

list1 = ['A','5','-0.5','D','0.5','-3','A','8','-0.7','C','4','1.6','D','1','0.6']

From this list I want to get a dictionary with letters as keys and lists of tuples of floats as values, so that should be as follows:

d = { "A" : [(5 ,-0.5), (8 ,-0.7)] , "D" : [(0.5 ,-3) , (1 , 0.6)] , "C" : [(4 , 1.6)] }

As you can see, the keys are letters and the values are tuples, which contain the next two elements. In the given list, they are str, but they must be float in d.

IMPORTANT: Only one loop is allowed and must be performed without importing any package.

CodePudding user response:

You can use defaultdict for this:

from collections import defaultdict
list1 = ['A','5','-0.5','D','0.5','-3','A','8','-0.7','C','4','1.6','D','1','0.6']
d = defaultdict(list)
for i in range(0, len(list1), 3):
    d[list1[i]].append((float(list1[i   1]), float(list1[i   2])))
d

Output

defaultdict(list,
            {'A': [(5.0, -0.5), (8.0, -0.7)],
             'D': [(0.5, -3.0), (1.0, 0.6)],
             'C': [(4.0, 1.6)]})

If you don't want to use import library, you can add another condition:

list1 = ['A','5','-0.5','D','0.5','-3','A','8','-0.7','C','4','1.6','D','1','0.6']
d = {}
for i in range(0, len(list1), 3):
    if list1[i] not in d:
        d[list1[i]] = []
    d[list1[i]].append((float(list1[i   1]), float(list1[i   2])))
d

Output

{'A': [(5.0, -0.5), (8.0, -0.7)],
 'D': [(0.5, -3.0), (1.0, 0.6)],
 'C': [(4.0, 1.6)]}

Edit: Add function to convert string to float

CodePudding user response:

Having fun with iterators:

it = iter(list1)
nums = zip(*[map(eval, it)]*2)
d = {}
for c in it:
    d.setdefault(c, []).append(next(nums))

Try it online!

Using eval because your desired output shows some numbers as ints despite your "must be float" request. Use float instead if floats are ok instead of ints.

CodePudding user response:

Here you go:

list1 = ['A','5','-0.5','D','0.5','-3','A','8','-0.7','C','4','1.6','D','1','0.6']
d={}
for x in range(0,len(list1),3):
  if list1[x] in d :
    d[list1[x]].append((float(list1[x 1]),float(list1[x 2])))
  else:
    d[list1[x]]=[(float(list1[x 1]),float(list1[x 2]))]

d is your new dictionary.

  • Related