How to get a list from a dictionary [duplicate] - python

This question already has answers here:
How can I get list of values from dict?
(7 answers)
Closed 5 years ago.
I want to extract the values from a dictionary and print them as a list. For example: If i have
letter = {"i": 3, "o": 2, "u": 2}
and want to extract 3,2, and 2 and print it as a list
[3, 2, 2]
How do I do this?
I've tried
print([x[::] for x in letter])
However, this prints out ['i', 'o', 'u'] and not [3, 2, 2].
Thank you for the help in advanced :)

There is a method in Python called .keys() that allows you to get the keys from a dict. Similarly, there is also a method called values() for the converse.
These are dict instance methods, ie:
myDict = { "i": 0, "t": 1, "f": 2 }
print(myDict.values())

You can just call dict.values()
Further details here

Try letter.values(), which gives you dict_values([3, 2, 2])
>>> letter = {"i": 3, "o": 2, "u": 2}
>>> print(list(letter.values()))
[3, 2, 2]

Related

Converting object into array in python [duplicate]

This question already has answers here:
Selecting elements of a Python dictionary greater than a certain value
(3 answers)
Closed 11 months ago.
I need to convert a PHP/JSON "object" (Python dict) into an array for filler words and show filler words with no count that will not be shown. How can I do this?
This is written as an object:
filler_word = {'um': 9, 'uh': 4, 'hmm': 0, 'mhm': 0, 'uh huh': 0}
This is how I want to have it into an array:
filler_word = ['um': 9, 'uh': 4, 'hmm': 0, 'mhm': 0, 'uh huh': 0]
This is how I want to show those filler words with 0 count that will not be shown:
filler_word = ['um': 9, 'uh': 4]
You are bringing PHP thinking to your Python coding. The two are very different. What you have in the first line is a dictionary, which is the equivalent of a PHP array, and is used like a PHP array.
Python lists do not have keys. So, this is a list:
mylist = [ 9, 4, 0, 0 ]
Use a dict comprehension:
{key: value for key,value in filler_word.items() if value > 0 }
{'um': 9, 'uh': 4}

Print evaluation of function calls and iterators [duplicate]

This question already has answers here:
Is it safe to rely on Python function arguments evaluation order? [duplicate]
(2 answers)
How to prove that parameter evaluation is "left to right" in Python?
(6 answers)
Order of execution of expressions in Python
(3 answers)
Does python have an arguments processing order well defined?
(2 answers)
Closed 5 years ago.
I would like to understand the way Python evaluates function calls inside print statements or, more particulary, what does the call for
next(some_iter) return? A mutable reference to the element in the next position or just a copy of the element in the next position when some_iter was last evaluated?
The following code:
def foo(val, arr=set()):
arr.add(val)
return arr
print(foo(1))
print(foo(2))
print(foo(1), foo(3), foo(0))
Returns the output:
{1}
{1, 2}
{0, 1, 2, 3} {0, 1, 2, 3} {0, 1, 2, 3}
Python calls the function three times, holding what seems to be a reference to arr, then, since sets are mutable, the output is as can be seen above. foo(1) return value was not saved, that is {1, 2} when it is called in order of the print statement.
However
lst = [1, 2, 3, 4]
def bar(a):
a = lst
a[0] = 17
return a
x = iter(lst)
y = iter(lst)
print(next(x), bar(lst), next(y), next(x))
print(lst)
Would print
1 [17, 2, 3, 4] 17 3
[17, 2, 3, 4]
I would have expected
17 [17, 2, 3, 4] 17 3
[17, 2, 3, 4]
That is for next to hold a reference to the first element of lst, which would later be changed to 17, and for that reference to be printed as 17 eventually, but it is computed first returning 1.
Why does it not happen? In what way is the next() or iters different?

Sort a python dictionary value which is a list [duplicate]

This question already has answers here:
How to sort list inside dict in Python?
(2 answers)
Closed 6 years ago.
I have a dictionary with the following structure, how can I sort each list within itself in ascending order?
mydictionary = {'1':[1,4,2], '2':[2,1,3], '3':[1,3,2]}
I want to have the dictionary sorted like this:
mydictionary_sorted = {'1':[1,2,4], '2':[1,2,3], '3':[1,2,3]}
>>> { x:sorted(y) for x,y in mydictionary.items() }
{'3': [1, 2, 3], '2': [1, 2, 3], '1': [1, 2, 4]}

why 2 and 4 remain in the 2 example? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 6 years ago.
I need to remove all unique objects in the given lists.
My code passes 1,3,4 checks but doesn't pass 2nd one, it returns [2,4], why not []?
def checkio(data):
for i in data:
if data.count(i) == 1 :
data.remove(i)
return data
if __name__ == "__main__":
assert isinstance(checkio([1]), list), "The result must be a list"
assert checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3], "1st example"
assert checkio([1, 2, 3, 4, 5]) == [], "2nd example"
assert checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5], "3rd example"
assert checkio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9], "4th example"
The problem here is that you are removing elements from a list while iterating through it, which you should never do.
The iteration for i in data keeps moving the index it's looking at forward. So, when you remove the first element in the list, the next item is moved to index 0 and the loop moves on to look at the element at index 1, skipping over the item that was moved to index 0.
Instead, you can build up a new list containing items that meet your criteria:
items = []
for i in data:
if (data.count(i) > 1):
items.append(i)
return items
Or do something like this:
return [i for i in l1 if l1.count(i) > 1]
The 'remove' function automatically recreates the list. So when "1" was removed, "2" was put in that slot, so it won't check that same position again, which is why alternating items are remaining. However, you can still implement the same function as you have, but instead work from the back of the list and iterate to the front:
def checkio(data):
for i in range(len(data)-1,-1,-1):
if data.count(data[i]) == 1 :
data.remove(data[i])
return data

How to order my dictionary in python? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In Python, how to I iterate over a dictionary in sorted order?
I need help in dictionaries. I have two dictionaries, and I want to add the values of identical keys in those two dictionaries. I need to make a list of summing the values that has the same key. I did the list but those values that their keys are the only ones in the two dictionaries are added after finishing all calculations. What I mean is:
dectionary1= {8: 2, 0: 6, 2: 5, 3: 34}
dectionary2= {8: 6, 1: 2, 3: 2}
My list must be:
summing= [6, 2, 5, 36, 8]
since it will take 0 and check whether there is 0 in dectionary 2, and then it will TAKE 1 (NOT 2) and check whether it's found in dectionary 1 in order to order the list.
I got this so far:
summing=[8, 6, 5, 36, 2]
Here it initially takes key (8) not (0)!! I want it to be in order.
To see my code, that what I got so far:
dic1= {8: 2, 0: 6, 2: 5, 3: 34}
dic2= {8: 6, 1: 2, 3: 2}
p=[]
for x in dic1:
if x in dic2:
g=dic1[x]+dic2[x]
p=p+[g]
else:
p=p+[dic1[x]]
for m in dic2:
if m in dic1:
p=p
else:
p=p+[dic2[m]]
I think if I can make the dictionaries ascendingly ordered, it will be much easier, but how?
My python is Wing IDE 3.2
Thank you
You have two options here, one is to use collections.OrderedDict(), but I think the easier option is simply to do it this way:
[dic1.get(x, 0)+dic2.get(x, 0)for x in sorted(dic1.keys() | dic2.keys())]
We first make a set of any keys in either of the dictionaries, sort this into the right order, and then loop over it with a list comprehension, adding the two values (or 0 if the value doesn't already exist).
>>> dic1= {8: 2, 0: 6, 2: 5, 3: 34}
>>> dic2= {8: 6, 1: 2, 3: 2}
>>> [dic1.get(x, 0)+dic2.get(x, 0)for x in sorted(dic1.keys() | dic2.keys())]
[6, 2, 5, 36, 8]
Note that this only works in 3.x, where dict.keys() returns a set-like dictionary view. If you want to do this in python 2.7.x, use dict.viewkeys() instead, earlier than that, set(dict.iterkeys()) would be optimal.

Categories