3

I want to create a dictionary from the following list

[{'fips': '01001', 'state': 'AL', 'name': 'Autauga County'}, {'fips': '20005', 'state': 'KS', 'name': 'Atchison County'}, {'fips': '47145', 'state': 'TN', 'name': 'Roane County'}]

The result should have the name as the key and 'United States' as the value.

eg:

{'Autauga County': 'United States', 'Atchison County' : 'United States',  'Roane County' : 'United States'}

I can do this with a couple of for loops but i want to learn how to do it using Dictionary Comprehensions.

Dhanushka Amarakoon
  • 3,502
  • 5
  • 31
  • 43

4 Answers4

11
in_list = [{'fips': '01001', 'state': 'AL', 'name': 'Autauga County'}, 
           {'fips': '20005', 'state': 'KS', 'name': 'Atchison County'},
           {'fips': '47145', 'state': 'TN', 'name': 'Roane County'}]

out_dict = {x['name']: 'United States' for x in in_list if 'name' in x}

Some notes for learning:

  • Comprehensions are only for Python 2.7 onwards
  • Dictionary comprehensions are very similar to list comprehensions except with curly braces {} (and keys)
  • In case you didn't know, you can also add more complicated control-flow after the for loop in a comprehension such as [x for x in some_list if (cond)]

For completeness, if you can't use comprehensions, try this

out_dict = {}

for dict_item in in_list:
    if not isinstance(dict_item, dict):
        continue

    if 'name' in dict_item:
        in_name = dict_item['name']
        out_dict[in_name] = 'United States'

As mentioned in the comments, for Python 2.6 you can replace the {k: v for k,v in iterator} with:

dict((k,v) for k,v in iterator)

You can read more about this in this question

Happy Coding!

Jamie Phan
  • 1,112
  • 7
  • 15
  • 1
    Oh my bad - so used to Python 3. I must say though, pretty new here and that's the fastest set of downvotes I've gotten - is it because of the lack of Python 2 support or is there something else? – Jamie Phan Jan 25 '17 at 11:20
  • @tehjoker yes, well, dictionary comprehensions only work for python 2.7+ so it's sort of a moot point... – juanpa.arrivillaga Jan 25 '17 at 11:23
  • Understood haha (it was really fast though), thought I did something terribly wrong. Will keep that in mind. Thanks! – Jamie Phan Jan 25 '17 at 11:24
  • 3
    I'm completely puzzled why you got downvotes. Don't feel bad for writing a Python 2.7 or 3 answer, without a version number in the question Python 3 is a good assumption. – Georg Schölly Jan 25 '17 at 11:24
  • 2
    I am puzzled too. I think it is safe to assume that when the question asks about dictionary comprehensions that we are talking about a Python version that supports dictionary comprehensions... – juanpa.arrivillaga Jan 25 '17 at 11:24
  • 1
    Haha thanks guys - I'm not particularly fussed with rep, I think answering questions is a great way to learn coding - and downvotes just make sure you produce the best code! On a side note, someone should give an answer with both Python 2.x and 3.x support, I look forward to it (haven't done Python 2 for a while) – Jamie Phan Jan 25 '17 at 11:28
  • Seems like it's a valid solution, I took the pitch fork out too quick once I seen the Error on my screen! I've changed my vote and began downloading Python 2.7+.....happy coding! – Alan Kavanagh Jan 25 '17 at 11:29
  • @K.J.Phan 2.6 support is quite simple, you can replace `{k: v for k,v in iterator}` with `dict((k, v) for k,v in iterator)`. Basically just passing a iterator over tuples to the dictionary constructor,, – Georg Schölly Jan 25 '17 at 21:40
2

Here's a little solution working for both python2.7.x and python 3.x:

data = [
    {'fips': '01001', 'state': 'AL', 'name': 'Autauga County'},
    {'fips': '20005', 'state': 'KS', 'name': 'Atchison County'},
    {'fips': '47145', 'state': 'TN', 'name': 'Roane County'},
    {'fips': 'xxx', 'state': 'yyy'}
]

output = {item['name']: 'United States' for item in data if 'name' in item}
print(output)
BPL
  • 9,632
  • 9
  • 59
  • 117
-1

The loop/generator version is:

location_list = [{'fips': '01001', 'state': 'AL', 'name': 'Autauga County'},
        {'fips': '20005', 'state': 'KS', 'name': 'Atchison County'},
        {'fips': '47145', 'state': 'TN', 'name': 'Roane County'}]
location_dict = {location['name']:'United States' for location in location_list}

Output:

{'Autauga County': 'United States', 'Roane County': 'United States',
 'Atchison County': 'United States'}

If you search on Stackoverflow for dictionary comprehension, solutions using the { } generator expression start to show up: Python Dictionary Comprehension

Community
  • 1
  • 1
UpSampler
  • 399
  • 2
  • 6
-2

That should do the trick for you

states_dict = [{'fips': '01001', 'state': 'AL', 'name': 'Autauga County'}, {'fips': '20005', 'state': 'KS', 'name': 'Atchison County'}, {'fips': '47145', 'state': 'TN', 'name': 'Roane County'}]

{states_dict[i]['name']:'United States' for i, elem in enumerate(states_dict)}
Tagc
  • 8,736
  • 7
  • 61
  • 114
BlackHawk
  • 37
  • 8
  • Just to get better understanding, any issues with that ?. I believe it works fine and I tested it – BlackHawk Jan 25 '17 at 11:27
  • 1
    @BlackHawk It's a confusing and inelegant way to accomplish something that can be done much simpler (see top-rated answers). – Tagc Jan 25 '17 at 11:33
  • Thanks for this and sorry my dump answer. I'm still learning and was trying to help only. – BlackHawk Jan 25 '17 at 11:45