본문 바로가기
<개인공부> - IT/[Python]

How to get a dict key in the list

by Aggies '19 2020. 6. 13.
반응형

 

Example: 

interfaceList = [{"Gi 0/1" : "Switch 1"}, {"Gi 0/2" : "Switch 2"}]

 

I want to get soley a str-type key from the list to look up a list of dict, which are Gi 0/1 and Gi 0/2. But, if I iterate and print the interfaceList and using keys() functions

for elem in interfaceList:
	print(elem.keys())

I get a dict_keys-type key instead like the right below output.

[Output]

dict_keys(['Gi 0/1'])
dict_keys(['Gi 0/2'])

In order to get a key such as Gi 0/1 or Gi 0/2, we can tweak the code as below.

for elem in interfaceList:
	key = list(elem.keys())[0]
	print(key)
반응형