4 examples of 'python get first item in dict' in Python

Every line of 'python get first item in dict' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
5def _find_dict_in_list(list_of_dict, key, val):
6 """Given a list of dictionaries, return the first dictionary that has the
7 given key:value pair.
8 """
9 try:
10 for d in list_of_dict:
11 if (key, val) in d.items():
12 return d
13 except TypeError:
14 pass
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

120def first_key(d):
121 if sys.version < '3':
122 return sorted(d.keys())[0]
123 else:
124 for key in sorted(d.keys()):
125 return key
50def first(iterable, default=None, key=None):
51 """
52 Return the first truthy value of an iterable.
53 Shamelessly stolen from https://github.com/hynek/first
54 """
55 if key is None:
56 for el in iterable:
57 if el:
58 return el
59 else:
60 for el in iterable:
61 if key(el):
62 return el
63 return default
315def __getitem__(self, key):
316 for k, v in self:
317 if key == k:
318 return v
319 raise KeyError

Related snippets