61

I have a dictionary like this:

myDict = { 'BigMeadow2_U4': (1609.32, 22076.38, 3.98), 'MooseRun': (57813.48, 750187.72, 231.25), 'Hwy14_2': (991.31, 21536.80, 6.47) } 

How can I get the first value of each item in my dicitionary?

I want in the end a list:

myList = [1609.32,57813.48,991.31] 
3
  • 1
    A dict is unordered. This means that there is no ordering of the elements in the dictionary - you need to access the values by the keys that they are associated with. So please explain why the elements in myList are ordered the way they are (first element of the values associated with keys in sorted order, perhaps?) Commented Feb 21, 2014 at 9:44
  • Dict is unordered. There is an Ordered Dict you can use but I forget if it's built in so you might need to import it. Commented Dec 20, 2023 at 20:57
  • Just looked it up. Dicts are now guaranteed to be ordered so you only need OrderedDict if you need the extra features. Because of this just iterate the dict. Commented Dec 20, 2023 at 20:59

7 Answers 7

82

Modern Python 3.x's can use iterator that has less overhead than constructing a list.

first_value = next(iter(my_dict.values())) 

Note that if the dictionary is empty you will get StopIteration exception and not None. To produce None in case of an empty dict, provide a default value to next():

first_value = next(iter(my_dict.values()), None) 

Since Python 3.7+ this is guaranteed to give you the first item.

Sign up to request clarification or add additional context in comments.

6 Comments

As of Python 3.7 dicts are now guaranteed to be ordered by insertion order
But this is not guaranteed to be the case in the future Python versions or non-CPython interpreters. It applies only for a certain CPython version.
No. It's a documented feature of Python, so other implementations should do it too if they claim to implement Python>=3.7. So PyPy does implement it (at least for PyPy 3.7+). So it's guaranteed into the future as much as anything in Python is.
"Guaranteed into the future" with Python still means that in a few months it'll probably require a new unintuitive joke of a syntax. In order to get the first value, get a list, construct an iterator, and call the function "next". Yeah, sure, whatever Python. I'll just spend half my workday googling again and looking forward to working with a real language again.
@EmanuelP if you have a bad day and want to rant, I suggest posting on Reddit. People here try to be helpful. We cannot fix all the issues in the world, like war, hunger and legacy quirks of programming languages. But we can make the day of some people better.
|
13

Try this way:

my_list = [elem[0] for elem in your_dict.values()] 

Offtop: I think you shouldn't use camelcase, it isn't python way

UPD: inspectorG4dget notes, that result won't be same. It's right. You should use collections.OrderedDict to implement this correctly.

from collections import OrderedDict my_dict = OrderedDict({'BigMeadow2_U4': (1609.32, 22076.38, 3.98), 'MooseRun': (57813.48, 750187.72, 231.25), 'Hwy14_2': (991.31, 21536.80, 6.47) }) 

5 Comments

Result won't be the same, always, given that a dictionary is an unordered data structure. Needs a stronger justification for the ordering of the elements of my_list
I can't find a linking saying that CamcelCase is not python way. legacy.python.org/dev/peps/pep-0008/#descriptive-naming-styles
they are just different naming styles, and many people just like the CamcelCase more ;P
Ok, as I now CamelCase isn't good for function names and variables. I googled a little and find this: stackoverflow.com/questions/159720/… Anyway, it isn't strict rule and I think you shouldn't be worried about that. It was just my notice
Isn't this one-liner going to iterate the whole dictionary when you only want to peek at one item?
4

A dictionary is not indexed, but it is in some way, ordered. The following would give you the first existing value:

list(myDict.values())[0] 

Comments

1

one lines...

myList = [myDict [i][0] for i in sorted(myDict.keys()) ] 

the result:

>>> print myList [1609.32, 991.31, 57813.48] 

Comments

0
myList = [] for k,v in myDict.items() myList.append(v[0]) 

Comments

0

If you want ordered dictionary, use:

from collections import OrderedDict ordered = OrderedDict( ('BigMeadow2_U4', (1609.32, 22076.38, 3.98)), ('MooseRun', (57813.48, 750187.72, 231.25)), ('Hwy14_2', (991.31, 21536.80, 6.47)) ) first_values = [v[0] for v in ordered.values()] 

The output order will be exactly as your input order.

4 Comments

Careful with that: since the input dictionary is unordered, they is no way of knowing how the items will be ordered when the OrderedDict is created from a regular dict. (see penultimate line in the class's doc)
Read my comment again ;) I'm saying you cannot tell if 'BigMeadow2_U4' will be the first value if you create the OrderedDict from a plain dict instead of adding them in the right order.
oh, yes, in this case you're right, changed it to tuples
-6

Try this.Type the dictionary and the position you want to print in the function

d = {'Apple': 1, 'Banana': 9, 'Carrot': 6, 'Baboon': 3, 'Duck': 8, 'Baby': 2} print(d) def getDictKeyandValue(dict,n): c=0 mylist=[] for i,j in d.items(): c+=1 if c==n: mylist=[i,j] break return mylist print(getDictKeyandValue(d,2)) 

2 Comments

Looks like C! And not in a good way.
I think he's playing for misère.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.