Reputation: 310
How to assign key and values to different variables in the dictionary within the list. I'm using for loop but is there any better approach that I can assign and use the values globally.
data = [{'country':[1,'US']}]
for i in data:
for j in i.items():
type = j[0]
rank = j[1][0]
country = j[1][0]
print(type)
print(rank)
print(country)
Upvotes: 2
Views: 72
Reputation: 16564
There is nothing wrong with your approach using for loop but you can do this to make it a little bit neater: (Also do not shadow the name "type")
data = [{'country': [1, 'US']}]
for i in data:
for k, v in i.items():
type_ = k
rank, country = v
print(type_)
print(rank)
print(country)
Or :
data = [{'country': [1, 'US']}]
for i in data:
for type_, (rank, country) in i.items():
print(type_)
print(rank)
print(country)
If there is only one dictionary inside your list you can do this as well :
data = [{'country': [1, 'US']}]
type_, (rank, country) = next(iter((data[0].items())))
print(type_)
print(rank)
print(country)
Upvotes: 1