converting list into dictionary with index as key [duplicate] - python

This question already has answers here:
One liner: creating a dictionary from list with indices as keys
(5 answers)
Why do I get "List index out of range" when trying to add consecutive numbers in a list using "for i in list"? [duplicate]
(4 answers)
Closed 4 years ago.
To convert a list into a dictionary with key as the index of the element and values as the value in the list. i have tried to create it but was facing errors.below is my current code
for each in list:
dict[each] = list[each]
what is wrong in my code. i am a beginner in python.

Try using enumerate! It's nifty:
list = ['a','b','c']
print(dict(enumerate(list))) # >>> {0: 'a', 1: 'b', 2: 'c'}
what is wrong with your code is that you are taking two elements of a list (by subscripting them with the list[value] syntax) and setting them equal to each other.
What you meant to do:
d = {}
l = ['a','b','c']
for k,v in enumerate(l):
d[k] = v
What this does:
Enumerating a sequence gives you a tuple where an integer is paired with the value of the sequence.Like in my list above, the enumerate(list) itself would be:
for k in enumerate([1,2,3]):
print(k)
Result: (0, 1)
(1, 2)
(2, 3)
The k and v in the loop first for loop I wrote unpacks the tuples (k= the index 0 of the tuple, v = the second), and the predefined dict (d in my case) sets the enumerate value (d[k], the key) to the value k (the second value of the tuple after enumeration)
Hope this makes sense!

dict = {}
for each in list:
dict[each] = list[each]
Take for array list = [1,2,34,22] an example
dict[1] = list[1] # list[1] = 2
dict[2] = list[2] # list[2] = 34
dict[34] = list[34] # Error size is just 4 , accessing list[34] will give index error
Try this simple code
a = [1,2,34,22]
dict = {}
for i in range(len(a)):
dict[i]=a[i]
print(dict)

the following code will work
lst = [1,2,3,4]
result = {i:j for i,j in enumerate(lst)}

Related

How to get dictionary keys using a tuple, where dictionary keys are stored in list and values in tuple

dictionary = {}
my_list = ['a','b','c','d']
for i in range(len(my_list)-1):
dictionary[my_list[i]] = (my_list[i],)
for i in sorted (dictionary.keys()):
k = dictionary[i]
"""code here"""
For the above code I need to get the output as :
a
b
c
I know if we put print(i), we will get the desired output, but the answer expected is in terms of K.
Actual answer is: print(k[0]),which I am unable to understand.
Thanks
Since you define values of dictionary equal to a tuple here:
dictionary[my_list[i]] = (my_list[i],)
k is a tuple which means for it to print the actual value you need to get the first item in k by using the following:
dictionary = {}
my_list = ['a','b','c','d']
for i in range(len(my_list)-1):
dictionary[my_list[i]] = (my_list[i],)
for i in sorted (dictionary.keys()):
k = dictionary[i]
print(k[0])
Output:
a
b
c
k[0] just gets the first item in the tuple ('a',). This makes it print a instead of ('a',).

Return elements of a list if equal to a condition [duplicate]

This question already has answers here:
if else in a list comprehension [duplicate]
(8 answers)
Closed 2 years ago.
I have list in shape a = [[aaa,1,0],[aba,1,2],[aca,0,3],...]. By using a list comprehension I'd like to compose a new list if the second element of a row is equal to lets say 1.
For now b = [x[1]==1 for x in a]] returns a boolean true false but I want those indexes return a new list.
try:
a = [[aaa,1,0],[aba,1,2],[aca,0,3],...]
output = [i for i in a if i[1] == 1]
or you can use filter which returns an iterator:
output = filter(lambda x: x[1] == 1, a)
I guess, this is the syntax you are looking for:
b = [x for x in a if x[1]==1]
b = [ i for i,item in enumerate(a) if a[i][1]==1]
This will return a list containing indices of element in a , that satisfies the condition
if u want the items itself make it
b = [item for i,item in enumerate(a) if a[i][1]==1]
Try this :
b = [i for i,j in enumerate(a) if j[1]==1]
It gives you the a list of indexes for which second item equals to 1. If you want to get a list of items of which second item is equal to 1,try this :
b = [i for i in a if i[1]==1]
If you want a slightly speedier version, use filter method :
b = filter(lambda i: i[1]==1, a)

How to add list to a dictionary? [duplicate]

This question already has an answer here:
Make dictionary from list
(1 answer)
Closed 4 years ago.
How can I add an already existing list into a dictionary?
Specifically, if I have:
lst = [["Hi"],["Monty"],["Python"],["snake"],["Anaconda"]]
And I was looking to get:
d = {0: "Hi", 1: "Monty", 2: "Python", 3: "snake", 4: "Anaconda"}
How would I go about doing this?
dict(enumerate(lst))
is your friend!
in your case:
dict(enumerate(itertools.chain.from_iterable((lst))))
The easiest way is with a dictionary comprehension. You can get the index of the sublist using the enumerate function.
lst = [["Hi"],["Monty"],["Python"],["snake"],["Anaconda"]]
d = {i: sublist[0] for i, sublist in enumerate(lst)}
You can also add each list item using a for loop.
d = {}
for i, sublist in enumerate(lst):
d[i] = sublist[0]
You can use enumerate:
newdict = {}
for i, j in enumerate(lst):
newdict[j] = i[0]
print(newdict)
You have a list of lists where each of the inner lists is holding one string. To turn that into a dictionary holding only the string, you will need to explicitly iterate through each item. You can do this with a dictionary comprehension.
d = {i: val[0] for i, val in enumerate(lst)}
or
d = {(i, val[0]) for i, val in enumerate(lst)}
Here we iterate over each index, inner list pair with val[0] taking the string out of the inner list.

Python printing single key/value pairs from a dict [duplicate]

This question already has answers here:
Get key by value in dictionary
(43 answers)
Closed 7 years ago.
Say I have the following code that makes a dict:
x = 0
myHash = {}
name = ["Max","Fred","Alice","Bobby"]
while x <= 3:
myHash[name[x]] = x
x += 1
l = sorted(myHash.values(), reverse=True)
largestNum = l[0]
# print myHash.getKeyFromValue(largestNum)
Is it possible to easily get the key that is paired to my largestNum variable without looping through the entire dict? Something like the pseudo code in the line at the bottom.
Note: I don't want to get a value from a key. I want the reverse of that.
Don't just sort the values. Sort the items by their values, and get the key for free.
from operator import itemgetter
l = sorted(myHash.items(), key=itemgetter(1), reverse=True)
largestKey, largestNum = l[0]
Note: If you only want the largest value, not the rest of the sort results, you can save some work and skip the full sorted work (reducing work from O(n log n) to O(n)):
largestKey, largestNum = max(myHash.items(), key=itemgetter(1))
For the general case of inverting a dict, if the values are unique, it's trivial to create a reversed mapping:
invert_dict = {v: k for k, v in orig_dict.items()}
If the values aren't unique, and you want to find all keys corresponding to a single value with a single lookup, you'd invert to a multi-dict:
from collections import defaultdict
invert_dict = defaultdict(set)
for k, v in orig_dict.items():
invert_dict[v].add(k)
# Optionally convert back to regular dict to avoid lookup auto-vivification in the future:
# invert_dict = dict(invert_dict)

Python: Remove list item if it is key for a given value from dictionary

I have a function h() that returns a tuple corresponding to the most common element in a list and its value from a dictionary called "Values" - so for example, if the most common element in list1 is a string "test" that occurs three times and that corresponds to Values = {"test":10}, then h(list1) = [3,10].
When two lists share the same element/frequency, I want to remove the most common element. Here is what I'm trying:
list1.remove([k for k,v in Values.items() if v == h(list1)[1]])
ValueError: list.remove(x): x not in list
How can I remove the key from a list based on its value in the Values dictionary?
Remove only expects a single element.
toremove = {k for k,v in Values.items() if v == h(list1)[1]]}
#either:
for r in toremove:
list1.remove(r)
#or (less efficient)
list1 = = [i for i in list1 if i not in toremove]

Categories

Resources