Mapping array to sequential numbers via dictionary [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 an array:
classes = ["banana","mango","apple"]
I am trying to print this array in a specific format where in each element has to be numbered in a particular sequence. The desired output is as follows:
classes = [{"banana" : 1, "mango" : 2, "apple" : 3}]
I tried using a for loop as follows:
classes = ["banana","mango","apple"]
counter = 0
dat = []
for x in classes:
counter=counter+1
d = x,":", counter
dat.append(d)
print(dat)
While this prints
[('banana', ':', 1), ('mango', ':', 2), ('apple', ':', 3)]
this is far from what I require. Can someone help?

You can enumerate the input list and reverse via a dictionary comprehension.
classes = ["banana","mango","apple"]
res = {v: k for k, v in enumerate(classes, 1)}
# {'apple': 3, 'banana': 1, 'mango': 2}
There seems to be no need to put this dictionary in a list, as in your desired output.

Related

How can I print the name of a variable from a list? [duplicate]

This question already has answers here:
How to print variable name in a list
(3 answers)
Closed 1 year ago.
I'm new to python and I've been trying to sort some variables and then print the names of the variables in sorted order, but I can't get further than this.
x = 0
y = 9
z = 3
numbers = [x,y,z]
numbers.sort(reverse=True)
for x in range(len(numbers)):
print(numbers[x])
I want it to print
y
z
x
But I don't know how to do this and I cant seem to find anything online
First, if you care about names associated with each value, you should be using a dict, not individual variables. Variable names are not data.
numbers = {'x': 0, 'y': 9, 'z': 3}
You can get the output you want by sorting the keys of the dict, but making comparisons based on the value associated with each key using the key argument to sorted.
for k in sorted(numbers, key=numbers.get, reversed=True):
print(k)
When deciding if a value v1 is less than v2, sorted will compare them using numbers.get: v1 < v2 if numbers.get(v1) < numbers.get(v2).
As already mentioned in the comments a list knows nothing about your variable names. If you care about the names you can use a dictionary which has a key-value structure. For instance you can use:
d = {'x' : 0, 'y':9, 'z' : 4}
d_sorted = {k: v for k, v in sorted(d.items(), key=lambda item:
item[1],reverse=True)}
To produce the following result:
{'y': 9, 'z': 4, 'x': 0}
Have also a look at where i got this code from.
dic ={'x':0,'y':9,'z':3}
for x in sorted( dic.items(), reverse=True, key=lambda item: item[1]):
print(x[0])
Use a dictionary to store the variable names and their values:
var_info = {"x": 0, "y": 9, "z": 3}
Then use a loop over the sorted items:
import operator
for item in sorted(var_info.items(), key=operator.itemgetter(1), reverse=True):
print(item[1])

Convert two lists to a dictionary but Sum the values for Same Keys [duplicate]

This question already has an answer here:
How to merge two lists into a dictionary and sum values for duplicate keys [duplicate]
(1 answer)
Closed 1 year ago.
This is my first time asking a question on stack overflow myself but have been using the resources here for quite a while - thanks!
list_1 = ['a','b','c','c']
list_2 = [2,2,2,2]
I want to combine both the lists and get add values of the same keys
my_dict = dict(zip(stream_ids, times))
but whenever I combine the lists to dictionaries - value for the key gets replaced by the last one
Output: {'a': 2, 'b': 2, 'c': 2}
I want both 'c' to be added to get a 4
What I want to get is
{'a': 2, 'b': 2, 'c': 4}
Any help would be really appreciated!
The most readable way would be to use a simple for loop:
stream_ids = ['a','b','c','c']
times = [2,2,2,2]
my_dict = {}
for idx, count in zip(stream_ids, times):
if idx in dict:
my_dict[idx] += count
else:
my_dict[idx] = count
You can probably do it in one line too using a lamda function and dictionary comprehension but that won't be very readable.
A dict will simply overwrite existing values. You have to build your dict by your own.
stream_ids = ['a','b','c','c']
times = [2,2,2,2]
my_dict = {}
for s, t in zip(stream_ids, times):
my_dict[s] = my_dict.get(s, 0) + t
print(my_dict) # {'a': 2, 'b': 2, 'c': 4}
A variant of other answers here, with collections.defaultdict:
from collections import defaultdict
stream_ids = ['a','b','c','c']
times = [2,2,2,2]
dict = defaultdict(int)
for idx, count in zip(stream_ids, times):
dict[idx] += count
since the default for a new integer is 0.

Transform multiple lists to dictionary of tuples [duplicate]

This question already has answers here:
How to map multiple lists to one dictionary?
(2 answers)
Closed 2 years ago.
I'm attempting to convert multiple lists into a dictionary where the initial list contains the keys.
For example:
list_keys = ['a' , 'b']
list_vals_1 = ['tick' , 'tack']
list_vals_2 = ['big' , 'small']
is transformed into:
expected = {}
expected['a'] = ('tick' , 'big')
expected['b'] = ('tack', 'small')
print('expected' , expected)
I could transform the lists using into a dictionary using:
mappings = {}
i = 0
for l in list_keys :
mappings[l] = (list_vals_1[i] , list_vals_2[i])
i = i + 1
Is there a cleaner/better solution using Python to accomplish this ?
try zip
dict(zip(list_keys, zip(list_vals_1, list_vals_2)))
{'a': ('tick', 'big'), 'b': ('tack', 'small')}
Use zip():
>>> {k: (v1, v2) for k, v1, v2 in zip(list_keys, list_vals_1, list_vals_2)}
{'a': ('tick', 'big'), 'b': ('tack', 'small')}
Also, for what it's worth, you could have used enumerate() to improve your existing solution:
for i, k in enumerate(list_keys):
mappings[k] = (list_vals_1[i], list_vals_2[i])
By the way, note that l is a bad variable name since it looks like 1 and I. I used k instead - short for "key".

Update item in dict comprehension python [duplicate]

This question already has answers here:
Using a dictionary to count the items in a list
(8 answers)
Closed 2 years ago.
words = ['rocky','mahesh','surendra','mahesh','rocky','mahesh','deepak','mahesh','mahesh','mahesh','surendra']
words_count = {}
for word in words:
words_count[word] = words_count.get(word, 0) + 1
print(words_count)
# Expected Output
# {'rocky': 2, 'mahesh': 6, 'surendra': 2, 'deepak': 1}
In this example, I just want to modify value of dict key while dict comprehension
Note: not looking other way to find occurrence/count of each key in dict.
You can use collections.Counter:
from collections import Counter
words_count = Counter(words)
You could count that without using any import and using as few .counts as possible following way:
words = ['rocky','mahesh','surendra','mahesh','rocky','mahesh','deepak','mahesh','mahesh','mahesh','surendra']
words_count = {i:words.count(i) for i in set(words)}
print(words_count) # {'surendra': 2, 'mahesh': 6, 'rocky': 2, 'deepak': 1}
Converting list to set will result in unique values.
A short, simple, one-liner code:
{i:words.count(i) for i in words}
Here, we create a dictionary based on the count of the word.
Gives:
{'rocky': 2, 'mahesh': 6, 'surendra': 2, 'deepak': 1}

How to take several items from dictionary [duplicate]

This question already has answers here:
Extract a subset of key-value pairs from dictionary?
(14 answers)
Filter dict to contain only certain keys?
(22 answers)
Closed 5 years ago.
Dictionary:
d = {'a':[2,3,4,5],
'b':[1,2,3,4],
'c':[5,6,7,8],
'd':[4,2,7,1]}
I want to have d_new which containes only b and c items.
d_new = {'b':[1,2,3,4],
'c':[5,6,7,8]}
I want a scalable solution
EDIT:
I also need a method to create a new dictionary by numbers of items:
d_new_from_0_to_2 = {'a':[2,3,4,5],
'b':[1,2,3,4]}
If you want a general way to pick particular keys (and their values) from a dict, you can do something like this:
d = {'a':[2,3,4,5],
'b':[1,2,3,4],
'c':[5,6,7,8],
'd':[4,2,7,1]}
selected_keys = ['a','b']
new_d = { k: d[k] for k in selected_keys }
Gives:
{'a': [2, 3, 4, 5], 'b': [1, 2, 3, 4]}
I think that in Python 2.6 and earlier you would not be able to use a dict comprehension, so you would have to use:
new_d = dict((k,d[k]) for k in selected_keys)
Is this what you want?
new_d = dict(b=d.get('b'), c=d.get('c'))

Categories