28

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]
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
ustroetz
  • 5,802
  • 16
  • 47
  • 74
  • 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?) – inspectorG4dget Feb 21 '14 at 09:44

7 Answers7

26

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.

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

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • As of Python 3.7 dicts are now guaranteed to be ordered by insertion order – DavidW Mar 17 '22 at 22:34
  • 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. – Mikko Ohtamaa Mar 18 '22 at 10:06
  • 3
    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. – DavidW Mar 18 '22 at 10:13
11

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) })
Andrii Rusanov
  • 4,405
  • 2
  • 34
  • 54
  • 1
    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` – inspectorG4dget Feb 21 '14 at 09:46
  • 1
    I can't find a linking saying that *CamcelCase* is not python way. http://legacy.python.org/dev/peps/pep-0008/#descriptive-naming-styles – zhangxaochen Feb 21 '14 at 09:57
  • they are just different naming styles, and many people just like the CamcelCase more ;P – zhangxaochen Feb 21 '14 at 10:01
  • Ok, as I now CamelCase isn't good for function names and variables. I googled a little and find this: http://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variable-and-function-names Anyway, it isn't strict rule and I think you shouldn't be worried about that. It was just my notice – Andrii Rusanov Feb 21 '14 at 10:02
  • Isn't this one-liner going to iterate the whole dictionary when you only want to peek at one item? – PPC Feb 04 '18 at 14:06
1

one lines...

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

the result:

>>> print myList 
[1609.32, 991.31, 57813.48]
Houcheng
  • 2,674
  • 25
  • 32
0
myList = []  
for k,v in myDict.items()  
    myList.append(v[0])
linpingta
  • 2,324
  • 2
  • 18
  • 36
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.

DominiCane
  • 1,263
  • 3
  • 16
  • 29
  • Careful with that: since the [input dictionary is unordered](https://docs.python.org/3/library/collections.html#ordereddict-objects), 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) – Silmathoron Apr 13 '16 at 06:52
  • @Silmathoron , you are wrong. Read in the docs: [Ordered dictionaries are just like regular dictionaries but they remember the **order that items were inserted**](https://docs.python.org/3/library/collections.html#ordereddict-objects) – DominiCane Apr 14 '16 at 07:52
  • 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. – Silmathoron Apr 14 '16 at 10:49
  • oh, yes, in this case you're right, changed it to tuples – DominiCane Apr 16 '16 at 09:22
-4

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))
Community
  • 1
  • 1
-4

for getting first value

print(getDictKeyandValue(d,1))

Community
  • 1
  • 1