-2

I have a sample code here containing a list of dicts,

[{'uri': 1, 'name': 'one'}, {'uri': 2, 'name': 'two'}, {'uri': 3, 'name': 'three'}]

The output I expect is the value from the key uri

[1, 2, 3]
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Sappaa
  • 1
  • 5
  • Write a loop perhaps? What level of Python knowledge do you have? Maybe a tutorial would be a better place for you to learn or just plain reading of the documentation to get an overview of the tools the language gives you? Also, what's the deal with tagging this as both Python 2.7 and 3.x? Which version are you actually targetting? – Ulrich Eckhardt Feb 21 '21 at 12:13

4 Answers4

3

You can use list comprehension:

uri_nums = [dict['uri'] for dict in my_list]
2

A list comprehension should do the trick:

myDict = [{'uri': 1, 'name': 'one'}, {'uri': 2, 'name': 'two'}, {'uri': 3, 'name': 'three'}]
result = [d['uri'] for d in myDict]
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

A list comprehension is the most readable way to do this:

[item['uri'] for item in my_dictionary]
Thomas
  • 174,939
  • 50
  • 355
  • 478
1

There are several ways to do that. I like using python‘s list comprehension which is something you will find very useful.

my_original_list = [{'uri': 1, 'name': 'one'}, {'uri': 2, 'name': 'two'}, {'uri': 3, 'name': 'three'}]
my_list = [elem["uri"] for elem in my_original_list]
Ouss
  • 2,912
  • 2
  • 25
  • 45