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.
Related
I want to remove some items from specific places. for example, I have list [a,b,c,d,e,f,g,h,i]. the number of items in this list constantly changes.
That is why I need special method that is helps to remove items from same place. Now the modified list should be like that: list [a,b,c,d,e,f,i]. g and h should always be removed.
Do you want to remove the second- and third-last item from the list?
This can be achieved like this:
del lst[-3:-1]
If you create dictionaries with necessary indexes you can use them to create a new list.
lst = ['a','b','c','d','e','f','g','h','i']
other = ['a','y','b','c','d','e','g','h','l']
indexed_lst = {i: item for i, item in enumerate(lst)}
indexed_other = {i: item for i, item in enumerate(other)}
[item for i, item in indexed_lst.items() if indexed_lst.get(i, None) != indexed_other.get(i, None) ]
You can remove from the list either by index or by value. In either case it is a good practice to check if the index/value is present in the list. As for removing an item from the list you could use one of the below based on what info is available / output required.
Remove an item by index and get its value: pop()
# where i is the index of the value to be removed
if i < len(lst)
result = l.pop(i)
Remove items by index or slice: del()
# where i is the index of the value to be removed
if i < len(lst) :
lst.del(i)
Remove an item by value: remove()
# where `h` is the value to be removed
if 'h' in lst:
lst.remove('h')
You could also remove items from a list based on a given condition, in which case you could use list comprehensions
l = list(range(10))
# Remove all the odd numbers
print([i for i in l if i % 2 != 0])
ahh i understand your answer, if you use index like this
Remove items by index, specific place
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for index,item in enumerate(lst) if index != 6 and index != 7]
print(lst)
or Remove items by Value
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for item in lst if item != 'g' and item != 'h']
print(lst)
Use the .pop() to pop off any given index off the list
lst = ['a','b','c','d','e','f','g','h','i']
lst = [item for item in lst if item != 'g' and item != 'h']
print(lst)
if you have more input, tell me
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)}
I have python method defined as follows. I try to match dictionary elements which matches to clientname parameter
def loadSites(self, fpath, clientname):
keylist = [re.findall(clientname,k) for k in self.cacheDictionary.keys()]
for items in keylist:
print(items)
When I print the list I get;
['testClient']
['testClient']
[]
[]
[]
[]
I expect to get only two elements. What Im doing wrong here?
Also, how Can I delete that item from my dictionary?
re.findall returns an empty list if the pattern is not found. You can simply filter these out. Note that when you iterate a dict, you automatically iterate the keys:
keylist = filter(None, (re.findall(clientname,k) for k in self.cacheDictionary))
# Python3: if you want to persist a list
# keylist = list(filter(None, (re.findall(clientname,k) for k in self.cacheDictionary)))
for items in keylist:
print(items)
Update:
If you want to delete all keys from the dict that match your pattern and in fact contain the string, there are many options tat do not require regular expressions, e.g.:
ks = [k for k in self.cacheDictionary if clientName in k]
for k in ks:
self.cacheDictionary.pop(k)
# del self.cacheDictionary[k]
Or just comprehend a new dict form scratch in one iteration:
self.cd = {k: v for k, v in self.cd.items() if clientName not in k}
If you want only two elements return only when there is a match.
keylist = [re.findall(clientname,k) if(re.findall(clientname,k)) else None for k in self.cacheDictionary.keys()]
for items in keylist:
print(items)
I have a dictionary of dictionary for example:
d={'object1':{'time1':['value1','value2'],'time2':['value1','value4']},
'object2':{'time1':['value1','value6'],'time2':['value7','value8']}}
How can I iterate over the dictionary such that I can find value1 appears 3 times in total?
You can iterate over the values & count like this:
n = 0
for list_data in d.values():
if 'value1' in list_data:
n = n + 1
print(n)
Try with list.count(x):
d={'object1':{'time1':['value1','value1','value2'],'time2':['value1','value4']},'object2':{'time1':['value1','value6'],'time2':['value7','value8']}}
cnt =[item for l in [v2 for v1 in d.values() for v2 in v1.values()] for item in l].count('value1')
print(cnt) # print 4
You may use the combination of collections.Counter and itertools.chain to achieve this as:
>>> from itertools import chain
>>> from collections import Counter
>>> d={'time1':['value1','value2'],'time2':['value1','value4'],'time3':['value1','value5']}
>>> counter_dict = Counter(chain(*d.values()))
# ^ dict holding the count of each value
In order to fetch the count of 'value1' in your counter_dict, you need to just access the value of this key as:
>>> counter_dict['value1']
3
Well the tricky way is:
print(str(d).count('value1'))
but you can always just do a nested loop.
This may not be the most elegant solution but it works for your nested dictionary problem:
lst = d.values()
sub_val = [temp.values() for temp in lst]
d_val = [item for sublist in sub_val for item in sublist]
d_val = [item for sublist in d_val for item in sublist]
count = d_val.count('value1')
lst is a list of nested dictionaries. sub_val creates a nested list of values for each nested dictionary. This results in a list of double nested list hence d_val flattening appears twice. Finally, count returns number of occurrences of value1 in the flattened list d_val.
I am new to Python.
Say I have a list:
list = ['A','B','C','D']
The key for each item respectively here is 0,1,2,3 - right?
Now I am going to loop through it with a for loop...
for item in list:
print item
That's great, I can print out my list.
How do I get the key here? For example being able to do:
print key
print item
on each loop?
If this isn't possible with a list, where keys are not declared myself, is it possible with a Dictionary?
Thanks
The answer is different for lists and dicts.
A list has no key. Each item will have an index. You can enumerate a list like this:
>>> l = ['A','B','C','D']
>>> for index, item in enumerate(l):
... print index
... print item
...
0
A
1
B
2
C
3
D
I used your example here, but called the list 'l', to avoid a clash with a reserved word.
If you iterate over a dict, you are handed the key:
>>> d = {0: 'apple', 1: 'banana', 2: 'cherry', 3: 'damson', }
>>> for k in d:
... print k
... print d[k]
...
0
apple
1
banana
2
cherry
3
damson
You want the index, not the key. For this you can use enumerate:
for index, item in enumerate(l):
print index
print item
This is mentioned in the section Looping Techniques in the Python tutorial which also covers looping over dictionaries while getting both the key and the value.
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave
You should use a dictionary, anyway you could do something like:
for index, item in enumerate(yourlist):
print "index:%d item:%s" % (index, item)