2

I have a problem with a dictionary that I want to split into two others.

dico={'GA1': {'main': 1, 'middle': 1, 'sub': 1}, 
      'GA2': {'main': 1, 'middle': 1, 'sub': 2}, 
      'GA3': {'main': 1, 'middle': 1, 'sub': 3}, 
      'GA4': {'main': 1, 'middle': 1, 'sub': 4}, 
      'GA5': {'main': 1, 'middle': 1, 'sub': 5}, 
      'GA6': {'main': 1, 'middle': 1, 'sub': 6}, 
      'GA7': {'main': 1, 'middle': 1, 'sub': 7}, 
      'GA8': {'main': 1, 'middle': 1, 'sub': 8}, 
      'GA9': {'main': 1, 'middle': 1, 'sub': 9}, 
      'GA10': {'main': 1, 'middle': 1, 'sub': 10}}

I want to put GA2 and GA6 to GA10 in a dictionary d1 and GA1 and GA3 to GA5 in a dictionary d2.

When I transform it into a list, I end up with tupples like,

list(dico.items())[0] 

which gives ('GA1', {'main': 1, 'middle': 1, 'sub': 1}) When I want to set this into my new dictionary,

d2 = {}
d2.update(list(dico.items())[0])

I end up with "builtins.ValueError: dictionary update sequence element #0 has length 3; 2 is required"

Is a dictionary an invalid format for a tuple element ?

Thanks for your help

Alexandre

A.Joly
  • 2,317
  • 2
  • 20
  • 25

3 Answers3

1

Did you mean this?

d2.update([list(dico.items())[0]])

You can initialise a dictionary with a list of tuples. You were providing only a single tuple, not inside a list. Use the [] to initialise a singleton list and pass that:

{'GA10': {'middle': 1, 'main': 1, 'sub': 10}}

Also, doing list(dico.items()) and then taking the 0th element is wasteful. If you can, consider changing your approach to your problem.

cs95
  • 379,657
  • 97
  • 704
  • 746
0

Create a list of the keys you want, then use a dict comprehension. Code below creates a dictionary, d2, with GA1, GA8 and GA9, key-value pairs.

newkeys = ['GA1', 'GA8', 'GA9']

d2 = {k: dico[k] for k in set(newkeys) & set(dico.keys())}

see Filter dict to contain only certain keys? for more info

Andrew
  • 950
  • 7
  • 24
0
d1 = { k:dico[k] for k in ['GA2','GA6','GA10'] }
print (d1)

Output:

{'GA2': {'main': 1, 'middle': 1, 'sub': 2}, 'GA6': {'main': 1, 'middle': 1, 'sub': 6}, 'GA10': {'main': 1, 'middle': 1, 'sub': 10}}
Transhuman
  • 3,527
  • 1
  • 9
  • 15