initialize dict with keys,values from two list [duplicate] - python

This question already has answers here:
How can I make a dictionary (dict) from separate lists of keys and values?
(21 answers)
Closed 4 years ago.
I have read this link
But how do I initialize the dictionary as well ?
say two list
keys = ['a','b','c','d']
values = [1,2,3,4]
dict = {}
I want initialize dict with keys & values

d = dict(zip(keys, values))
(Please don't call your dict dict, that's a built-in name.)

In Python 2.7 and python 3, you can also make a dictionary comprehension
d = {key:value for key, value in zip(keys, values)}
Although a little verbose, I found it more clear, as you clearly see the relationship.

Related

access a dict inside of a dict using strings? [duplicate]

This question already has answers here:
Access nested dictionary items via a list of keys?
(20 answers)
Closed 7 months ago.
I need to make a method that lets you navigate dicts of various depths using a simple string.
How can I make get_from_dict(dict, "images.player.left") work? thaks
Split the string, and then look up the keys in a loop.
>>> def get_from_dict(d, keys):
... for key in keys.split("."):
... d = d[key]
... return d
...
>>> get_from_dict({"images": {"player": {"left": "tada!"}}}, "images.player.left")
'tada!'

How do you find the first item in a dictionary? [duplicate]

This question already has answers here:
How do you find the first key in a dictionary?
(12 answers)
Closed 2 years ago.
I am trying to get the first item I inserted in my dictionary (which hasn't been re-ordered).
For instance:
_dict = {'a':1, 'b':2, 'c':3}
I would like to get the tuple ('a',1)
How can I do that?
Before Python 3.6, dictionaries were un-ordered, therefore "first" was not well defined. If you wanted to keep the insertion order, you would have to use an OrderedDict: https://docs.python.org/2/library/collections.html#collections.OrderedDict
Starting from Python 3.6, the dictionaries keep the insertion order by default ( see How to keep keys/values in same order as declared? )
Knowing this, you just need to do
first_element = next(iter(_dict.items()))
Note that since _dict.items() is not an iterator but is iterable, you need to make an iterator for it by calling iter.
The same can be done with keys and values:
first_key = next(iter(_dict))
first_value = next(iter(_dict.values()))

Extract n top elements from dictionary [duplicate]

This question already has answers here:
5 maximum values in a python dictionary
(5 answers)
Closed 4 years ago.
I have created a dictionary in python. I have sorted the dictionary with the following instruction.
dict = {}
dict[identifier] = dst
sorted_dict = sorted(dict.items(), key=operator.itemgetter(1))
print sorted_dict
Here identifier is key and dst is a value
I want to retrieve first N elements from the dictionary. How I can do that?
Use slicing to extract n elements of the list
>>> print(sorted_dict[:n])
collectons.Counter It's the way to go:
from collections import Counter
count_dict = Counter(the_dict)
print(count_dict.most_common(n))
Here you have a live example

Merge two lists,one as keys, one as values, into a dict in Python [duplicate]

This question already has answers here:
How do I combine two lists into a dictionary in Python? [duplicate]
(6 answers)
Closed 7 years ago.
Is there any build-in function in Python that merges two lists into a dict? Like:
combined_dict = {}
keys = ["key1","key2","key3"]
values = ["val1","val2","val3"]
for k,v in zip(keys,values):
combined_dict[k] = v
Where:
keys acts as the list that contains the keys.
values acts as the list that contains the values
There is a function called array_combine that achieves this effect.
Seems like this should work, though I guess it's not one single function:
dict(zip(["key1","key2","key3"], ["val1","val2","val3"]))
from here: How do I combine two lists into a dictionary in Python?

Is there a "one-liner" way to get a list of keys from a dictionary in sorted order? [duplicate]

This question already has answers here:
How can I get a sorted copy of a list?
(2 answers)
Closed 28 days ago.
The list sort() method is a modifier function that returns None.
So if I want to iterate through all of the keys in a dictionary I cannot do:
for k in somedictionary.keys().sort():
dosomething()
Instead, I must:
keys = somedictionary.keys()
keys.sort()
for k in keys:
dosomething()
Is there a pretty way to iterate through these keys in sorted order without having to break it up in to multiple steps?
for k in sorted(somedictionary.keys()):
doSomething(k)
Note that you can also get all of the keys and values sorted by keys like this:
for k, v in sorted(somedictionary.iteritems()):
doSomething(k, v)
Can I answer my own question?
I have just discovered the handy function "sorted" which does exactly what I was looking for.
for k in sorted(somedictionary.keys()):
dosomething()
It shows up in Python 2.5 dictionary 2 key sort
Actually, .keys() is not necessary:
for k in sorted(somedictionary):
doSomething(k)
or
[doSomethinc(k) for k in sorted(somedict)]

Categories