Answers for "get first n values of dictionary python"

1

python return first n key values pairs from dictionary

# Basic syntax:
{key: dictionary[key] for key in list(dictionary)[:number_keys]}

# Note, number_keys is the number of key:value pairs to return from the
#	dictionary, not including the number_keys # itself
# Note, Python is 0-indexed
# Note, this formula be adapted to return any slice of keys from the 
#	dictionary following similar slicing rules as for lists

# Example usage 1:
dictionary = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
{key: dictionary[key] for key in list(dictionary)[:2]}
--> {'a': 3, 'b': 2} # The 0th to 1st key:value pairs

# Example usage 2:
dictionary = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
{key: dictionary[key] for key in list(dictionary)[2:5]}
--> {'c': 3, 'd': 4, 'e': 5} # The 2nd to 4th key:value pairs
Posted by: Guest on October-04-2020
1

get n items from dictionary python

list(islice(d.iteritems(), n))
'Update for Python 3.6
list(islice(d.items(), n))
Posted by: Guest on April-21-2020
0

python get first value in a dictionary

# Dictionary of string and int
word_freq = {
    'Hello' : 56,
    "try"    : 23,
    'test'  : 43,
    'This'  : 78,
    'Way'   : 11
}
# Get first value from dictionary
first_value = list(word_freq.values())[0]
print('First Value: ', first_value)

# Output:
# First Value:  56
Posted by: Guest on May-19-2021

Code answers related to "get first n values of dictionary python"

Python Answers by Framework

Browse Popular Code Answers by Language