Home > OS >  Python Code to store 2 values that are paired together
Python Code to store 2 values that are paired together

Time:10-26

city = ['michigan','toronto;,michigan','denver','michigan','toronto']

for line in lines:
  code <>
  print ("Found ", count_value,"matching ",city)

Expected output: Michigan : 3 Totonto : 2 denver : 1

How do i store count_value to reference or map to city, so i can print the top 3 cities that appeared the most in the list the loop is going though. I have done the code and can count the number of times a city is found in the list, but how do i print the top 3 highest count of cities in the list

CodePudding user response:

What youre looking for is called a dictionary; Which is really easy in python. You need to create a dictionary with the cities (they might need default values at first) then when you do your finding logic, assign that city the value (here is an untested example):

dict = {'michigan','toronto;,michigan','denver','michigan','toronto'}
for line in lines:
  code <>
  dict[city] = count_value

CodePudding user response:

You can use a Counter() which automatically accumulates the total number of occurrences in your list and sets it to the index values.

from collections import Counter
city = ['michigan', 'toronto', 'michigan', 'denver', 'michigan', 'toronto']
print(Counter(city)) # Outputs -> Counter({'michigan': 3, 'toronto': 2, 'denver': 1})

# To sort by most frequent cities first.
print(Counter(city).most_common()) # ('michigan', 3), ('toronto', 2), ('denver', 1)

To get the exact output that you want, you can just iterate over the list and insert the values for each city into a string:

from collections import Counter
city = ['michigan', 'toronto', 'michigan', 'denver', 'michigan', 'toronto']

city = Counter(city).most_common() # Convert city into a Counter of all the city occurrences.

totalCityString = ""
for key in city: totalCityString  = key[0]   ": "   str(key[1])   " "

print(totalCityString) # Outputs -> 'michigan: 3 toronto: 2 denver: 1'
  • Related