0

I am extracting some values from a dictionary in order to create another dictionary as follows:

from collections import defaultdict

a_lis = []
b_lis = []
for d in response['A']:
    a_lis.append(d['B'])
    b_lis.append(d['C'])
print(a_lis)
print(b_lis)

defaultdict(None, zip(a_lis,b_lis))

I decided to use default dict because I would like to have repeated elements inside my final dictionary. However, when I run the above code I get this:

defaultdict(None,
            {'Fruit': 'PAR',
             'Brand': 'best',
             'date': 'imorgon',
             'type': 'true',
             'class': 'Första klass',
             'time': '2018-10-25',
             'number': 10})

How can I take the second element of the tuple in order to get just:

            {'Fruit': 'PAR',
             'Brand': 'best',
             'date': 'imorgon',
             'type': 'true',
             'class': 'Första klass',
             'time': '2018-10-25',
             'number': 10}

I tried to:

defaultdict(None, zip(a_lis,b_lis))[1]

However it is not working

anon
  • 836
  • 2
  • 9
  • 25

1 Answers1

1

There isn't a "second element", in fact there isn't a tuple. That's just a representation of the defaultdict which is printing the default value, ie None. You access the dict just like any other:

d = defaultdict(None,
        {'Fruit': 'PAR',
         'Brand': 'best',
         'date': 'imorgon',
         'type': 'true',
         'class': 'Första klass',
         'time': '2018-10-25',
         'number': 10})

print(d['Fruit'])  #  -> 'PAR'

(Although I don't understand your justification for using the defaultdict here; since your default is None, it won't help you at all in having 'repeated elements'.)

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Is there any way to remove that representation? – anon Oct 24 '18 at 13:28
  • Yes, the justification is that I would like to have a different `Fruit` values in the same dictionary. For example `{'Fruit': 'PAR', 'Fruit':'PER', 'Brand': 'best', 'date': 'imorgon', 'type': 'true', 'class': 'Första klass', 'time': '2018-10-25', 'number': 10}` As far as I know, with a simple dictionary you cant do this. – anon Oct 24 '18 at 13:34
  • 2
    You have a pretty serious misunderstanding of what a defaultdict is. It will not *in any way at all* allow you to have multiple 'Fruit' keys. That is impossible in any kind of dictionary. And no, there is no way to remove that representation, but *there isn't any need to* as it is just a convenience for the shell. – Daniel Roseman Oct 24 '18 at 13:39
  • @Daniel: I suppose OP is being guided in some manner by [this popular answer](https://stackoverflow.com/a/1731989/1566221), without understanding exactly what is being proposed there. – rici Oct 24 '18 at 20:33