0

I created the dictionary named as Colors.

Colors = {'col1': 'Red', 'col2': 'Orange', 'col3': 'Yellow', 'col4': 'Yellow'} 

Q) Create a new Dictionary object colors_new from the colors Dictionary, having the keys col1 and col2 (Instruction – Use the fromkeys() method)? is it possible to use fromkeys()?

My coding is :

Colors = {'col1': 'Red', 'col2': 'Orange', 'col3': 'Yellow', 'col4': 'Yellow'}

print(Colors)

Col={ }

Colors_new={ }

print(Colors_new)

Colors_new = dict.fromkeys(Colors.keys())

print(Colors_new)

OUTPUT

{'col1': 'Red', 'col2': 'Orange', 'col3': 'Yellow', 'col4': 'Yellow'}
{}
{'col1': None, 'col2': None, 'col3': None, 'col4': None}

2 Answers2

1

Yes this is indeed possible.

colors_new = dict.fromkeys(Colors.keys()[:2])
Tim Körner
  • 385
  • 2
  • 9
0

Is this maybe what you want?

Colors = {'col1': 'Red', 'col2': 'Orange', 'col3': 'Yellow', 'col4': 'Yellow'}
print(Colors)
Col={ }
Colors_new={ }
print(Colors_new)
# if you want the new dictionary with only the keys
Colors_new = dict.fromkeys([k for k in Colors.keys() if k in ["col1", "col2"]])
print(Colors_new)
# if you want the new dictionary with keys and values
Colors_new = {k:v for k,v in Colors.items() if k in ["col1", "col2"]}
print(Colors_new)
Nikaido
  • 4,443
  • 5
  • 30
  • 47