-1

Dictionary:

d = {'a':[2,3,4,5],
     'b':[1,2,3,4],
     'c':[5,6,7,8],
     'd':[4,2,7,1]}

I want to have d_new which containes only b and c items.

d_new = {'b':[1,2,3,4],
         'c':[5,6,7,8]}

I want a scalable solution

EDIT:

I also need a method to create a new dictionary by numbers of items:

d_new_from_0_to_2 = {'a':[2,3,4,5],
                     'b':[1,2,3,4]}
Ladenkov Vladislav
  • 1,247
  • 2
  • 21
  • 45
  • And I **want to you write some code**. I guess we're both going to be disappointed, today. – SiHa Apr 20 '17 at 11:27

2 Answers2

3

If you want a general way to pick particular keys (and their values) from a dict, you can do something like this:

d = {'a':[2,3,4,5],
     'b':[1,2,3,4],
     'c':[5,6,7,8],
     'd':[4,2,7,1]}

selected_keys = ['a','b']

new_d = { k: d[k] for k in selected_keys }

Gives:

{'a': [2, 3, 4, 5], 'b': [1, 2, 3, 4]}

I think that in Python 2.6 and earlier you would not be able to use a dict comprehension, so you would have to use:

new_d = dict((k,d[k]) for k in selected_keys)
khelwood
  • 55,782
  • 14
  • 81
  • 108
1

Is this what you want?

new_d = dict(b=d.get('b'), c=d.get('c'))
Christos Papoulas
  • 2,469
  • 3
  • 27
  • 43