2

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)
1
  • 2
    Is there only ever going to be a single item in the list? What are you trying to do with the values you extract? Commented Sep 29, 2021 at 14:29

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

If there are multiple dictionaries in list data = [{'country':[2,'US']},{'county':[1,'RS']}] then how to print max value of all dictionaries and also country name in that list for eg: 'US' here.
@swarna I think it's better to post a new question for this.
I posted as new question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.