python how to output single values from a list of dictionaries

Question:

I have a list of dictionaries with the following values:

[{'IP Address': '5.161.105.105', 'Port': '80', 'Code': 'US', 'Country': 'United States', 'Anonymity': 'elite proxy', 'Google': 'no', 'Https': 'yes', 'Last Checked': '5 secs ago'}, 

{'IP Address': '186.251.64.10', 'Port': '8085', 'Code': 'BR', 'Country': 'Brazil', 'Anonymity': 'elite proxy', 'Google': 'no', 'Https': 'yes', 'Last Checked': '5 secs ago'}, 

{'IP Address': '144.76.241.45', 'Port': '7890', 'Code': 'DE', 'Country': 'Germany', 'Anonymity': 'elite proxy', 'Google': 'no', 'Https': 'yes', 'Last Checked': '5 secs ago'}]

proxy = [{'IP Address': '5.161.105.105', 'Port': '80', 'Code': 'US', 'Country': 'United States', 'Anonymity': 'elite proxy', 'Google': 'no', 'Https': 'yes', 'Last Checked': '5 secs ago'}]

print(proxy)]

Output:
[{'IP Address': '5.161.105.105', 'Port': '80', 'Code': 'US', 'Country': 'United States', 'Anonymity': 'elite proxy', 'Google': 'no', 'Https': 'yes', 'Last Checked': '5 secs ago'}]


expected output:

5.161.105.105

80

Asked By: Emil Budnitskiy

||

Answers:

You can use a list comprehension like this:

servers = [
    {'IP Address': '5.161.105.105', 'Port': '80', 'Code': 'US', 'Country': 'United States', 'Anonymity': 'elite proxy', 'Google': 'no', 'Https': 'yes', 'Last Checked': '5 secs ago'},
    {'IP Address': '186.251.64.10', 'Port': '8085', 'Code': 'BR', 'Country': 'Brazil', 'Anonymity': 'elite proxy', 'Google': 'no', 'Https': 'yes', 'Last Checked': '5 secs ago'},
    {'IP Address': '144.76.241.45', 'Port': '7890', 'Code': 'DE', 'Country': 'Germany', 'Anonymity': 'elite proxy', 'Google': 'no', 'Https': 'yes', 'Last Checked': '5 secs ago'}
]
urls = [
    ("https://" if server['Https'] == 'yes' else "http://") +
    f"{server['IP Address']}:{server['Port']}"
    for server in servers
]
print(urls)

['https://5.161.105.105:80', 'https://186.251.64.10:8085', 'https://144.76.241.45:7890']
Answered By: James McGuigan

The object you show is a list of dictionaries.
In order to get the first item (dictionary in that case) you can access it with lst[0].
In order to access a value in the dictionary you can access it by its key by dct[key].

So bottom line if you only want the first IP and port you can do:

values = [{...}, {...}, {...}]  # your list of dictionaries
first_dict = values[0]
ip_address = first_dict['IP Address']
port = first_dict['Port']
Answered By: Razko
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.