Choropleth Map in python using plotly without State Codes. - python

I have the following code to plot a choropleth Map in python.
data = [dict(
type="choropleth",
autocolorscale= True,
locations = df[statename],
z = df[z].astype(float),
locationmode = 'USA-states',
text = df[state],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 2
)),
colorbar = dict(title = title)
)]
layout = dict(title = title,
geo=dict(scope="usa",showlakes = True,lakecolor = 'rgb(255, 255, 255)'))
iplot(go.Figure(data=data,layout=layout),validate=False)
Is it possible to plot the map using just the State Names as input to locations or is it necessary to have the two Letter State Codes. When i use the state codes it works but when i use the state names it just gives me an empty map.

There might be a way to change the value passed to the argument locationmode to take state names instead of state codes. As an alternative if there's a dataframe statesdf with a column statesdf['state'] containing the state name you can use the below code to create state codes from state names:
state_codes = {
'District of Columbia' : 'dc','Mississippi': 'MS', 'Oklahoma': 'OK',
'Delaware': 'DE', 'Minnesota': 'MN', 'Illinois': 'IL', 'Arkansas': 'AR',
'New Mexico': 'NM', 'Indiana': 'IN', 'Maryland': 'MD', 'Louisiana': 'LA',
'Idaho': 'ID', 'Wyoming': 'WY', 'Tennessee': 'TN', 'Arizona': 'AZ',
'Iowa': 'IA', 'Michigan': 'MI', 'Kansas': 'KS', 'Utah': 'UT',
'Virginia': 'VA', 'Oregon': 'OR', 'Connecticut': 'CT', 'Montana': 'MT',
'California': 'CA', 'Massachusetts': 'MA', 'West Virginia': 'WV',
'South Carolina': 'SC', 'New Hampshire': 'NH', 'Wisconsin': 'WI',
'Vermont': 'VT', 'Georgia': 'GA', 'North Dakota': 'ND',
'Pennsylvania': 'PA', 'Florida': 'FL', 'Alaska': 'AK', 'Kentucky': 'KY',
'Hawaii': 'HI', 'Nebraska': 'NE', 'Missouri': 'MO', 'Ohio': 'OH',
'Alabama': 'AL', 'Rhode Island': 'RI', 'South Dakota': 'SD',
'Colorado': 'CO', 'New Jersey': 'NJ', 'Washington': 'WA',
'North Carolina': 'NC', 'New York': 'NY', 'Texas': 'TX',
'Nevada': 'NV', 'Maine': 'ME'}
statesdf['state_code'] = statesdf['state'].apply(lambda x : state_codes[x])

Related

Reduce States to Abbreviations

I'm trying to clean a dataset that has the states either as abbreviations or fully spelled out. I need to make them all into abbreviations.
Any cheats to do this?
This is what I've come up with, but I'm still not getting the right output. What am I missing
states = []
for c in by_state['order state']:
if len(c)==2:
states = c.upper()
else:
map(abbr.get,c)
Here is an approach.
import re
"""Table to Map States to Abbreviations Courtesy https://gist.github.com/Quenty/74156dcc4e21d341ce52da14a701c40c"""
statename_to_abbr = {
# Other
'District of Columbia': 'DC',
# States
'Alabama': 'AL',
'Montana': 'MT',
'Alaska': 'AK',
'Nebraska': 'NE',
'Arizona': 'AZ',
'Nevada': 'NV',
'Arkansas': 'AR',
'New Hampshire': 'NH',
'California': 'CA',
'New Jersey': 'NJ',
'Colorado': 'CO',
'New Mexico': 'NM',
'Connecticut': 'CT',
'New York': 'NY',
'Delaware': 'DE',
'North Carolina': 'NC',
'Florida': 'FL',
'North Dakota': 'ND',
'Georgia': 'GA',
'Ohio': 'OH',
'Hawaii': 'HI',
'Oklahoma': 'OK',
'Idaho': 'ID',
'Oregon': 'OR',
'Illinois': 'IL',
'Pennsylvania': 'PA',
'Indiana': 'IN',
'Rhode Island': 'RI',
'Iowa': 'IA',
'South Carolina': 'SC',
'Kansas': 'KS',
'South Dakota': 'SD',
'Kentucky': 'KY',
'Tennessee': 'TN',
'Louisiana': 'LA',
'Texas': 'TX',
'Maine': 'ME',
'Utah': 'UT',
'Maryland': 'MD',
'Vermont': 'VT',
'Massachusetts': 'MA',
'Virginia': 'VA',
'Michigan': 'MI',
'Washington': 'WA',
'Minnesota': 'MN',
'West Virginia': 'WV',
'Mississippi': 'MS',
'Wisconsin': 'WI',
'Missouri': 'MO',
'Wyoming': 'WY',
}
def multiple_replace(lookup, text):
"""Perform substituions that map strings in the lookup table to valuees (modification from https://stackoverflow.com/questions/15175142/how-can-i-do-multiple-substitutions-using-regex-in-python)"""
# re.IGNORECASE flags allows provides case insensitivity (i.e. matches New York, new york, NEW YORK, etc.)
regex = re.compile(r'\b(' + '|'.join(lookup.keys()) + r')\b', re.IGNORECASE)
# For each match, look-up corresponding value in dictionary and peform subsstituion
# we convert match to title to capitalize first letter in each word
return regex.sub(lambda mo: lookup[mo.string.title()[mo.start():mo.end()]], text)
if __name__ == "__main__":
text = """United States Census Regions are:
Region 1: Northeast
Division 1: New England (Connecticut, Maine, Massachusetts, New Hampshire, Rhode Island, and Vermont)
Division 2: Mid-Atlantic (New Jersey, New York, and Pennsylvania)
Region 2: Midwest (Prior to June 1984, the Midwest Region was designated as the North Central Region.)[7]
Division 3: East North Central (Illinois, Indiana, Michigan, Ohio, and Wisconsin)
Division 4: West North Central (Iowa, Kansas, Minnesota, Missouri, Nebraska, North Dakota, and South Dakota)"""
print(multiple_replace(statename_to_abbr, text))
Output Example
United States Census Regions are:Region 1: NortheastDivision 1: New England (CT, ME, MA, NH, RI, and VT)Division 2: Mid-Atlantic (NJ, NY, and PA)Region 2: Midwest (Prior to June 1984, the Midwest Region was designated as the North Central Region.)[7]Division 3: East North Central (IL, IN, MI, OH,and WI)Division 4: West North Central (IA, KS, MN, MO,NE, ND, and SD)
Thanks for the help. I've final found all the answers to my use-case, so here is what I needed in case anyone else needs it.
#Creates new dataframe with two columns,removes all the NaN values
by_state = sales[['order state','total']].dropna()
#Map a dictionary of abbreviations to the dataframe
by_state['order state'] = by_state['order state'].map(abbr).fillna(by_state['order state'])
#Map values that were not capitalized correctly
by_state['order state'] = by_state['order state'].apply(lambda x:x.title()).map(abbr).fillna(by_state['order state'])
#Convert all abbreviations to uppercase
by_state['order state'] = by_state['order state'].apply(lambda x:x.upper())
#Remove a period after a abbreviation
by_state['order state'] = by_state['order state'].apply(lambda x:x.split('.')[0])

pandas - Modify column values based on dictionary values

I have an CSV file containing a column "State" which contains US State names in full like: "New Jersey", "California", etc.
I want to modify this column so that they contain abbreviations instead of the full name like "NJ", "CA"...
To do this, I already have a dictionary that maps the state name to its abbreviation
us_state_abbrev = {
'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA', 'Colorado': 'CO',
'Connecticut': 'CT', 'Delaware': 'DE', 'Florida': 'FL', 'Georgia': 'GA', 'Hawaii': 'HI', 'Idaho': 'ID',
'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA', 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA',
'Maine': 'ME', 'Maryland': 'MD', 'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS',
'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH', 'New Jersey': 'NJ',
'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC', 'North Dakota': 'ND', 'Ohio': 'OH', 'Oklahoma': 'OK',
'Oregon': 'OR', 'Pennsylvania': 'PA', 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD',
'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virginia': 'VA', 'Washington': 'WA',
'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY'}
How do I loop through the column in my CSV file AND the dictionary and replace the full state name with the abbreviation?
Here's the code I wrote but it doesn't work:
with open(emp_file, 'r', errors='ignore') as fileHandle:
reader = csv.reader(fileHandle)
for row in reader:
for state, abbrev in us_state_abbrev.items():
if row[4] == state:
row[4] = abbrev
What am I doing wrong here? Please help.
import pandas as pd
df = pd.read_csv(emp_file)
then, assuming you know which column you want to edit:
df['State'] = df['State'].map(us_state_abbrev).fillna(df['State'])
Note: the last part deals with State entries not present in your dictionary

Append cleaned data to dictionary using if and loop technique

I have a dataset to clean and organize. Here is the link of the data set
https://github.com/irJERAD/Intro-to-Data-Science-in-Python/blob/master/MyNotebooks/university_towns.txt
So what I am trying to do is to clean this data set to the dictionary with the format {State: Town) for example {'Alabama': 'Auburn', Alabama: 'Florence'....'Wyoming': 'Laramie')
Here is my code:
import re
univ_towns = open('university_towns.txt',encoding='utf-8').readlines()
state_list = []
d={}
for name in univ_towns:
if "[ed" in name:
statename = re.sub('\[edit]\n$', '', name)
state_list.append(statename)
len_state = len(state_list)
elif "(" in name:
sep = ' ('
townname = name.split(sep, 1)[0]
if "," in townname:
sep = ','
townname = townname.split(sep, 1)[0]
d[state_list[len_state-1]] = townname
d
However, the code of my output only gives the results with only the last town appended in the dictionary. I am sure there is something no right with the loop logic but I can't really figure out what is wrong. Here is the output of my code:
{'Alabama': 'Tuskegee',
'Alaska': 'Fairbanks',
'Arizona': 'Tucson',
'Arkansas': 'Searcy',
'California': 'Whittier',
'Colorado': 'Pueblo',
'Connecticut': 'Willimantic',
'Delaware': 'Newark',
'Florida': 'Tampa',
'Georgia': 'Young Harris',
'Hawaii': 'Manoa',
'Idaho': 'Rexburg',
'Illinois': 'Peoria',
'Indiana': 'West Lafayette',
'Iowa': 'Waverly',
'Kansas': 'Pittsburg',
'Kentucky': 'Wilmore',
'Louisiana': 'Thibodaux',
'Maine': 'Waterville',
'Maryland': 'Westminster',
'Massachusetts': 'Framingham',
'Michigan': 'Ypsilanti',
'Minnesota': 'Winona',
'Mississippi': 'Starkville',
'Missouri': 'Warrensburg',
'Montana': 'Missoula',
'Nebraska': 'Wayne',
'Nevada': 'Reno',
'New Hampshire': 'Rindge',
'New Jersey': 'West Long Branch',
'New Mexico': 'Silver City',
'New York': 'West Point',
'North Carolina': 'Winston-Salem',
'North Dakota': 'Grand Forks',
'Ohio': 'Wilberforce',
'Oklahoma': 'Weatherford',
'Oregon': 'Newberg',
'Pennsylvania': 'Williamsport',
'Rhode Island': 'Providence',
'South Carolina': 'Spartanburg',
'South Dakota': 'Vermillion',
'Tennessee': 'Sewanee',
'Texas': 'Waco',
'Utah': 'Ephraim',
'Vermont': 'Northfield',
'Virginia': 'Chesapeake',
'Washington': 'University District',
'West Virginia': 'West Liberty',
'Wisconsin': 'Whitewater',
'Wyoming': 'Laramie'}
Try using defaultdict:
from collections import defaultdict
d = defaultdict(list)
for name in univ_towns:
if "[ed" in name:
statename = re.sub('\[edit]\n$', '', name)
state_list.append(statename)
len_state = len(state_list)
elif "(" in name:
sep = ' ('
townname = name.split(sep, 1)[0]
if "," in townname:
sep = ','
townname = townname.split(sep, 1)[0]
d[state_list[len_state-1]].append(townname)
As you can see, the only major difference is at the end where you use append instead of =. The way you had it before will only return one city rather than all cities, which is what you seem to want, unless I'm misunderstanding.

Python random.choice method without repeats?

I'm trying to improve this code which asks the user to say what the state capital is when given a state, but I've noticed that sometimes it will repeat a state and ask it twice.
I tried using random.sample instead, but I got an error "TypeError: Unhashable type: 'list'. Here is the code that works (but repeats) with the random.sample commented out:
capitals_dict = {
'Alabama': 'Montgomery',
'Alaska': 'Juneau',
'Arizona': 'Phoenix',
'Arkansas': 'Little Rock',
'California': 'Sacramento',
'Colorado': 'Denver',
'Connecticut': 'Hartford',
'Delaware': 'Dover',
'Florida': 'Tallahassee',
'Georgia': 'Atlanta',
'Hawaii': 'Honolulu',
'Idaho': 'Boise',
'Illinois': 'Springfield',
'Indiana': 'Indianapolis',
'Iowa': 'Des Moines',
'Kansas': 'Topeka',
'Kentucky': 'Frankfort',
'Louisiana': 'Baton Rouge',
'Maine': 'Augusta',
'Maryland': 'Annapolis',
'Massachusetts': 'Boston',
'Michigan': 'Lansing',
'Minnesota': 'St. Paul',
'Mississippi': 'Jackson',
'Missouri': 'Jefferson City',
'Montana': 'Helena',
'Nebraska': 'Lincoln',
'Nevada': 'Carson City',
'New Hampshire': 'Concord',
'New Jersey': 'Trenton',
'New Mexico': 'Santa Fe',
'New York': 'Albany',
'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck',
'Ohio': 'Columbus',
'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem',
'Pennsylvania': 'Harrisburg',
'Rhode Island': 'Providence',
'South Carolina': 'Columbia',
'South Dakota': 'Pierre',
'Tennessee': 'Nashville',
'Texas': 'Austin',
'Utah': 'Salt Lake City',
'Vermont': 'Montpelier',
'Virginia': 'Richmond',
'Washington': 'Olympia',
'West Virginia': 'Charleston',
'Wisconsin': 'Madison',
'Wyoming': 'Cheyenne',
}
import random
states = list(capitals_dict.keys())
for i in [1, 2, 3, 4, 5]:
state = random.choice(states)
#state = random.sample(states, 5)
capital = capitals_dict[state]
capital_guess = input('What is the capital of ' + state + '?')
if capital_guess == capital:
print('Correct! Nice job!')
else:
print('Incorrect. The Capital of ' + state + ' is ' + capital + '.')
print('All done.')
I also tried just using the dictionary name capitals_dict like this:
random.sample(capitals_dict, 5)
but I got a different error then found out that I can't use dictionaries like that.
You can create a list of all keys in the dictionary by passing the dictionary to the list() function first, then sample from that list:
sample = random.sample(list(capitals_dict), 5)
You can also pass in the dict.keys() dictionary view:
sample = random.sample(capitals_dict.keys(), 5)
but internally random.sample() will just convert that to a sequence too (a tuple()) so using list() is actually more efficient here.
The exception you encountered actually tells you this:
>>> random.sample(capitals_dict, 5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/.../lib/python3.4/random.py", line 311, in sample
raise TypeError("Population must be a sequence or set. For dicts, use list(d).")
TypeError: Population must be a sequence or set. For dicts, use list(d).
# ^^^^^^^^^^^^^^^^^^^^^^^
Demo:
>>> import random
>>> capitals_dict = {
... 'Alabama': 'Montgomery',
... 'Alaska': 'Juneau',
... 'Arizona': 'Phoenix',
... 'Arkansas': 'Little Rock',
... 'California': 'Sacramento',
... # ... elided ...
... }
>>>
>>> random.sample(list(capitals_dict), 5)
['Maryland', 'Mississippi', 'Wisconsin', 'Texas', 'West Virginia']
To incorporate that into your code:
import random
for state in random.sample(list(capitals_dict), 5):
capital = capitals_dict[state]
capital_guess = input('What is the capital of {}?'.format(state))
if capital_guess == capital:
print('Correct! Nice job!')
else:
print('Incorrect. The Capital of {} is {}.'.format(state, capital))
I also replaced your string concatenations with str.format() calls to put values into string templates instead.
Try doing it this way. which just samples the state names:
import random
num_queries = 5
for state in random.sample(capitals_dict.keys(), num_queries):
capital = capitals_dict[state]
capital_guess = input('What is the capital of ' + state + '?')
if capital_guess == capital:
print('Correct! Nice job!')
else:
print('Incorrect. The Capital of ' + state + ' is ' + capital + '.')
print('All done.')
While you could also use:
for state in random.sample(list(capitals_dict), num_queries):
because list(dictionary) will implicitly return a list of the dictionary's keys, but I prefer making what's going on explicit.
If anyone reading this wants a decent US States Capitals quizzer, I updated the code to include tracking the users score. It will ask all 50 states in a random order, and it will also let you skip and quit any time.
capitals_dict = {
'Alabama': 'Montgomery',
'Alaska': 'Juneau',
'Arizona': 'Phoenix',
'Arkansas': 'Little Rock',
'California': 'Sacramento',
'Colorado': 'Denver',
'Connecticut': 'Hartford',
'Delaware': 'Dover',
'Florida': 'Tallahassee',
'Georgia': 'Atlanta',
'Hawaii': 'Honolulu',
'Idaho': 'Boise',
'Illinois': 'Springfield',
'Indiana': 'Indianapolis',
'Iowa': 'Des Moines',
'Kansas': 'Topeka',
'Kentucky': 'Frankfort',
'Louisiana': 'Baton Rouge',
'Maine': 'Augusta',
'Maryland': 'Annapolis',
'Massachusetts': 'Boston',
'Michigan': 'Lansing',
'Minnesota': 'St. Paul',
'Mississippi': 'Jackson',
'Missouri': 'Jefferson City',
'Montana': 'Helena',
'Nebraska': 'Lincoln',
'Nevada': 'Carson City',
'New Hampshire': 'Concord',
'New Jersey': 'Trenton',
'New Mexico': 'Santa Fe',
'New York': 'Albany',
'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck',
'Ohio': 'Columbus',
'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem',
'Pennsylvania': 'Harrisburg',
'Rhode Island': 'Providence',
'South Carolina': 'Columbia',
'South Dakota': 'Pierre',
'Tennessee': 'Nashville',
'Texas': 'Austin',
'Utah': 'Salt Lake City',
'Vermont': 'Montpelier',
'Virginia': 'Richmond',
'Washington': 'Olympia',
'West Virginia': 'Charleston',
'Wisconsin': 'Madison',
'Wyoming': 'Cheyenne',
}
import random
counterQuestions = 0 # Represents the number of questions asked to the user
counterCorrect = 0
print('Enter the name of the State Capital with proper spelling. Enter "skip" to skip or "quit" to quit')
for state in random.sample(list(capitals_dict), 50):
capital = capitals_dict[state]
capital_guess = input('What is the capital of {}? '.format(state))
if capital_guess == 'skip':
#print('The Capital of {} is {}.'.format(state, capital)) #study mode - use comment feature to turn this on/off.
counterQuestions = counterQuestions + 1
continue
elif capital_guess == 'quit':
break
elif capital_guess == capital:
print('Correct! Nice job!')
counterCorrect = counterCorrect + 1
counterQuestions = counterQuestions + 1
else:
print('Incorrect. The Capital of {} is {}.'.format(state, capital))
counterQuestions = counterQuestions + 1
score = (counterCorrect / counterQuestions) * 100
counterIncorrect = counterQuestions - counterCorrect
print('All done. Your score is ' + str(score) + '% correct, or ' + str(counterCorrect) + ' out of ' + str(counterQuestions) + ' (' + str(counterIncorrect) + ' incorrect)')

How do I convert a Django QuerySet into list of dicts?

How can I convert a Django QuerySet into a list of dicts? I haven't found an answer to this so I'm wondering if I'm missing some sort of common helper function that everyone uses.
Use the .values() method:
>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]
Note: the result is a QuerySet which mostly behaves like a list, but isn't actually an instance of list. Use list(Blog.objects.values(…)) if you really need an instance of list.
The .values() method will return you a result of type ValuesQuerySet which is typically what you need in most cases.
But if you wish, you could turn ValuesQuerySet into a native Python list using Python list comprehension as illustrated in the example below.
result = Blog.objects.values() # return ValuesQuerySet object
list_result = [entry for entry in result] # converts ValuesQuerySet into Python list
return list_result
I find the above helps if you are writing unit tests and need to assert that the expected return value of a function matches the actual return value, in which case both expected_result and actual_result must be of the same type (e.g. dictionary).
actual_result = some_function()
expected_result = {
# dictionary content here ...
}
assert expected_result == actual_result
If you need native data types for some reason (e.g. JSON serialization) this is my quick 'n' dirty way to do it:
data = [{'id': blog.pk, 'name': blog.name} for blog in blogs]
As you can see building the dict inside the list is not really DRY so if somebody knows a better way ...
Type Cast to List
job_reports = JobReport.objects.filter(job_id=job_id, status=1).values('id', 'name')
json.dumps(list(job_reports))
You need DjangoJSONEncoder and list to make your Queryset to json, ref: Python JSON serialize a Decimal object
import json
from django.core.serializers.json import DjangoJSONEncoder
blog = Blog.objects.all().values()
json.dumps(list(blog), cls=DjangoJSONEncoder)
You do not exactly define what the dictionaries should look like, but most likely you are referring to QuerySet.values(). From the official django documentation:
Returns a ValuesQuerySet — a QuerySet subclass that returns
dictionaries when used as an iterable, rather than model-instance
objects.
Each of those dictionaries represents an object, with the keys
corresponding to the attribute names of model objects.
If you already have a query set you just use the list function to turn it into a list of dicts, eg:
list(MyModel.objects.values())
You can use the values() method on the dict you got from the Django model field you make the queries on and then you can easily access each field by a index value.
Call it like this -
myList = dictOfSomeData.values()
itemNumberThree = myList[2] #If there's a value in that index off course...
You could define a function using model_to_dict as follows:
from django.forms.models import model_to_dict
def queryset_to_list(qs,fields=None, exclude=None):
return [model_to_dict(x,fields,exclude) for x in qs]
Suppose your Model has the following fields
id
name
email
Run the following commands in Django shell
>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_list(qs)
>>>list
[{'id':1, 'name':'abc', 'email':'abc#ab.co'},{'id':2, 'name':'xyz', 'email':'xy#xy.co'}]
Say you want only the id and the name in the list of queryset dictionary
>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_list(qs,fields=['id','name'])
>>>list
[{'id':1, 'name':'abc'},{'id':2, 'name':'xyz'}]
Similarly, you can exclude fields in your output.
I found even a better solution:
This was my queryset:
queryset = TestDB.objects.values_list("country", "code")
Code above returned
<QuerySet [('Afghanistan', 'AF'), ('Albania', 'AL'), ('Algeria', 'DZ'), ('American Samoa', 'AS'), ('Andorra', 'AD'), ('Angola', 'AO'), ('Anguilla', 'AI'), ('Antarctica', 'AQ'), ('Antigua and Barbuda', 'AG'), ('Argentina', 'AR'), ('Armenia', 'AM'), ('Aruba', 'AW'), ('Australia', 'AU'), ('Austria', 'AT'), ('Azerbaijan', 'AZ'), ('Bahamas ', 'BS'), ('Bahrain', 'BH'), ('Bangladesh', 'BD'), ('Barbados', 'BB'), ('Belarus', 'BY'), '...(remaining elements truncated)...']>
and print(dict(queryset)) converted above into this:
{'Afghanistan': 'AF', 'Albania': 'AL', 'Algeria': 'DZ', 'American Samoa': 'AS', 'Andorra': 'AD', 'Angola': 'AO', 'Anguilla': 'AI', 'Antarctica': 'AQ', 'Antigua and Barbuda': 'AG', 'Argentina': 'AR', 'Armenia': 'AM', 'Aruba': 'AW', 'Australia': 'AU', 'Austria': 'AT', 'Azerbaijan': 'AZ', 'Bahamas ': 'BS', 'Bahrain': 'BH', 'Bangladesh': 'BD', 'Barbados': 'BB', 'Belarus': 'BY', 'Belgium': 'BE', 'Belize': 'BZ', 'Benin': 'BJ', 'Bermuda': 'BM', 'Bhutan': 'BT', 'Bolivia (Plurinational State of)': 'BO', 'Bonaire, Sint Eustatius and Saba': 'BQ', 'Bosnia and Herzegovina': 'BA', 'Botswana': 'BW', 'Bouvet Island': 'BV', 'Brazil': 'BR', 'British Indian Ocean Territory ': 'IO', 'Brunei Darussalam': 'BN', 'Bulgaria': 'BG', 'Burkina Faso': 'BF', 'Burundi': 'BI', 'Cabo Verde': 'CV', 'Cambodia': 'KH', 'Cameroon': 'CM', 'Canada': 'CA', 'Cayman Islands ': 'KY', 'Central African Republic ': 'CF', 'Chad': 'TD', 'Chile': 'CL', 'China': 'CN', 'Christmas Island': 'CX', 'Cocos (Keeling) Islands ': 'CC', 'Colombia': 'CO', 'Comoros ': 'KM', 'Congo (the Democratic Republic of the)': 'CD', 'Congo ': 'CG', 'Cook Islands ': 'CK', 'Costa Rica': 'CR', 'Croatia': 'HR', 'Cuba': 'CU', 'Curaçao': 'CW', 'Cyprus': 'CY', 'Czechia': 'CZ', 'Côte dIvoire': 'CI', 'Denmark': 'DK', 'Djibouti': 'DJ', 'Dominica': 'DM', 'Dominican Republic ': 'DO', 'Ecuador': 'EC', 'Egypt': 'EG', 'El Salvador': 'SV', 'Equatorial Guinea': 'GQ', 'Eritrea': 'ER', 'Estonia': 'EE', 'Eswatini': 'SZ', 'Ethiopia': 'ET', 'Falkland Islands [Malvinas]': 'FK', 'Faroe Islands ': 'FO', 'Fiji': 'FJ', 'Finland': 'FI', 'France': 'FR', 'French Guiana': 'GF', 'French Polynesia': 'PF', 'French Southern Territories ': 'TF', 'Gabon': 'GA', 'Gambia ': 'GM', 'Georgia': 'GE', 'Germany': 'DE', 'Ghana': 'GH', 'Gibraltar': 'GI', 'Greece': 'GR', 'Greenland': 'GL', 'Grenada': 'GD', 'Guadeloupe': 'GP', 'Guam': 'GU', 'Guatemala': 'GT', 'Guernsey': 'GG', 'Guinea': 'GN', 'Guinea-Bissau': 'GW', 'Guyana': 'GY', 'Haiti': 'HT', 'Heard Island and McDonald Islands': 'HM', 'Holy See ': 'VA', 'Honduras': 'HN', 'Hong Kong': 'HK', 'Hungary': 'HU', 'Iceland': 'IS', 'India': 'IN', 'Indonesia': 'ID', 'Iran (Islamic Republic of)': 'IR', 'Iraq': 'IQ', 'Ireland': 'IE', 'Isle of Man': 'IM', 'Israel': 'IL', 'Italy': 'IT', 'Jamaica': 'JM', 'Japan': 'JP', 'Jersey': 'JE', 'Jordan': 'JO', 'Kazakhstan': 'KZ', 'Kenya': 'KE', 'Kiribati': 'KI', 'Korea (the Democratic People Republic of)': 'KP', 'Korea (the Republic of)': 'KR', 'Kuwait': 'KW', 'Kyrgyzstan': 'KG', 'Lao People Democratic Republic ': 'LA', 'Latvia': 'LV', 'Lebanon': 'LB', 'Lesotho': 'LS', 'Liberia': 'LR', 'Libya': 'LY', 'Liechtenstein': 'LI', 'Lithuania': 'LT', 'Luxembourg': 'LU', 'Macao': 'MO', 'Madagascar': 'MG', 'Malawi': 'MW', 'Malaysia': 'MY', 'Maldives': 'MV', 'Mali': 'ML', 'Malta': 'MT', 'Marshall Islands ': 'MH', 'Martinique': 'MQ', 'Mauritania': 'MR', 'Mauritius': 'MU', 'Mayotte': 'YT', 'Mexico': 'MX', 'Micronesia (Federated States of)': 'FM', 'Moldova (the Republic of)': 'MD', 'Monaco': 'MC', 'Mongolia': 'MN', 'Montenegro': 'ME', 'Montserrat': 'MS', 'Morocco': 'MA', 'Mozambique': 'MZ', 'Myanmar': 'MM', 'Namibia': 'NA', 'Nauru': 'NR', 'Nepal': 'NP', 'Netherlands ': 'NL', 'New Caledonia': 'NC', 'New Zealand': 'NZ', 'Nicaragua': 'NI', 'Niger ': 'NE', 'Nigeria': 'NG', 'Niue': 'NU', 'Norfolk Island': 'NF', 'Northern Mariana Islands ': 'MP', 'Norway': 'NO', 'Oman': 'OM', 'Pakistan': 'PK', 'Palau': 'PW', 'Palestine, State of': 'PS', 'Panama': 'PA', 'Papua New Guinea': 'PG', 'Paraguay': 'PY', 'Peru': 'PE', 'Philippines ': 'PH', 'Pitcairn': 'PN', 'Poland': 'PL', 'Portugal': 'PT', 'Puerto Rico': 'PR', 'Qatar': 'QA', 'Republic of North Macedonia': 'MK', 'Romania': 'RO', 'Russian Federation ': 'RU', 'Rwanda': 'RW', 'Réunion': 'RE', 'Saint Barthélemy': 'BL', 'Saint Helena, Ascension and Tristan da Cunha': 'SH', 'Saint Kitts and Nevis': 'KN', 'Saint Lucia': 'LC', 'Saint Martin (French part)': 'MF', 'Saint Pierre and Miquelon': 'PM', 'Saint Vincent and the Grenadines': 'VC', 'Samoa': 'WS', 'San Marino': 'SM', 'Sao Tome and Principe': 'ST', 'Saudi Arabia': 'SA', 'Senegal': 'SN', 'Serbia': 'RS', 'Seychelles': 'SC', 'Sierra Leone': 'SL', 'Singapore': 'SG', 'Sint Maarten (Dutch part)': 'SX', 'Slovakia': 'SK', 'Slovenia': 'SI', 'Solomon Islands': 'SB', 'Somalia': 'SO', 'South Africa': 'ZA', 'South Georgia and the South Sandwich Islands': 'GS', 'South Sudan': 'SS', 'Spain': 'ES', 'Sri Lanka': 'LK', 'Sudan ': 'SD', 'Suriname': 'SR', 'Svalbard and Jan Mayen': 'SJ', 'Sweden': 'SE', 'Switzerland': 'CH', 'Syrian Arab Republic': 'SY', 'Taiwan (Province of China)': 'TW', 'Tajikistan': 'TJ', 'Tanzania, United Republic of': 'TZ', 'Thailand': 'TH', 'Timor-Leste': 'TL', 'Togo': 'TG', 'Tokelau': 'TK', 'Tonga': 'TO', 'Trinidad and Tobago': 'TT', 'Tunisia': 'TN', 'Turkey': 'TR', 'Turkmenistan': 'TM', 'Turks and Caicos Islands ': 'TC', 'Tuvalu': 'TV', 'Uganda': 'UG', 'Ukraine': 'UA', 'United Arab Emirates ': 'AE', 'United States Minor Outlying Islands ': 'UM', 'United States of America ': 'US', 'Uruguay': 'UY', 'Uzbekistan': 'UZ', 'Vanuatu': 'VU', 'Bolivarian Republic of Venezuela': 'VE', 'Viet Nam': 'VN', 'Virgin Islands (British)': 'VG', 'Virgin Islands (U.S.)': 'VI', 'Wallis and Futuna': 'WF', 'Western Sahara': 'EH', 'Yemen': 'YE', 'Zambia': 'ZM', 'Zimbabwe': 'ZW', 'Åland Islands': 'AX'}
Which I think you need in your case too (I guess).
values_list()¶
values_list(*fields, flat=False, named=False)
>>> Entry.objects.values_list('id', 'headline')
<QuerySet [(1, 'First entry'), ...]>
>>> from django.db.models.functions import Lower
>>> Entry.objects.values_list('id', Lower('headline'))
<QuerySet [(1, 'first entry'), ...]>
im a newbie in python and i love #David Wolever answer
user = Blog.objects.all()
user = list(user.values("username", "id"))
in my case i use this to print username
user = Blog.objects.all()
user = list(user.values("username"))
name = []
for i in user:
name.append(i["username"])
print(name)
# ["joe", "karen", "stuf"]
Simply put list(yourQuerySet).

Categories