-5
data = [
    {
        'name': 'Instagram',
        'follower_count': 346,
        'description': 'Social media platform',
        'country': 'United States'
    },
    {
        'name': 'Cristiano Ronaldo',
        'follower_count': 215,
        'description': 'Footballer',
        'country': 'Portugal'
    }]

how to print follower_count of any one of tthe two given dict

Celius Stingher
  • 17,835
  • 6
  • 23
  • 53

3 Answers3

1

You have a list of dictionaries, so what you’ll need to do is first index the array before accessing the follower count.

Something like:

data[i][“follower_count”]

Where i is some index in the array.

Chase McDougall
  • 211
  • 2
  • 7
  • and if i want to use random moddule one=random.choices(data) print([one]["follower_count"]) i m doing this its not working – Prabhpreet Singh Nov 12 '22 at 09:20
  • `random.choices` will return a list of `k` random selections. `k` defaults to `1`, so you’d need to access it via `one[0][“followers_count”]`. If you only want a single item returned it’d make more sense to use `random.choice` and you’ll receive one item which can be accessed using `one[“followers_count` – Chase McDougall Nov 12 '22 at 17:42
  • By putting `one` inside brackets it adds a dimension to the list, so you don’t want to be doing that – Chase McDougall Nov 12 '22 at 17:43
0

Basically, just select the dict you want (0 if you want the first) and then select the 'follower_count' value like so:

data[0]['follower_count']

0

If you want to have a random choice between 346 and 215 you should import random, the code should look like this if you want to print the 'follower_count' in any of those two dicts:

import random

data = [
    {
        'name': 'Instagram',
        'follower_count': 346,
        'description': 'Social media platform',
        'country': 'United States'
    },
    {
        'name': 'Cristiano Ronaldo',
        'follower_count': 215,
        'description': 'Footballer',
        'country': 'Portugal'
    }
]

x = random.randint(0,1)
print(data[x]['follower_count'])
Jethy11
  • 13
  • 5