Python 2,7 Dictionary Advice - python

I do not use dictionary objects often in Python. I've been working on a script that is going to require me to use a dictionary to store dynamically created list'esque information. How can I append a value to a list of values belonging to one key in a dictionary in Python? Is this possible? I would hope to be able to create this type of information from which I could pull later...
dict = {'PhysicalDrive0': '0', '1', '2', 'PhysicalDrive1': '0', '1'};
dict[PhysicalDrive0].append(3)
dict[PhysicalDrive1].append(2)
print dict[PhysicalDrive0]
<0, 1, 2, 3>
print dict[PhysicalDrive1]
<0, 1, 2>
Thanks!

Use a list as value, list will allow you to append new items:
>>> dic = {'PhysicalDrive0': ['0', '1', '2'], 'PhysicalDrive1': ['0', '1']}
>>> dic['PhysicalDrive0'].append('3')
>>> dic['PhysicalDrive1'].append('2')
>>> dic
{'PhysicalDrive1': ['0', '1', '2'], 'PhysicalDrive0': ['0', '1', '2', '3']}
To append to a value to a missing key you can use dict.setdefault, if the key is already present then it'll append value to the already present list otherwise creates a key with an empty list and then appends the value to it.
Demo:
#creates a new key PhysicalDrive3' and appends a value to it.
>>> dic.setdefault('PhysicalDrive3', []).append('3')
>>> dic
{'PhysicalDrive1': ['0', '1', '2'], 'PhysicalDrive0': ['0', '1', '2', '3'], 'PhysicalDrive3': ['3']}
>>> dic.setdefault('PhysicalDrive1', []).append('5')
>>> dic
{'PhysicalDrive1': ['0', '1', 2, '5'], 'PhysicalDrive0': ['0', '1', '2', 3], 'PhysicalDrive3': [3]}

You should look at collections.defaultdict if you can't simply store the value as a list literal...:
from collections import defaultdict
dd = defaultdict(list)
dd['Drive1'].append(3)
dd['Drive2'].append(6)
dd['Drive1'].append(2)
# defaultdict(<type 'list'>, {'Drive2': [6], 'Drive1': [3, 2]})

dict = {'PhysicalDrive0': ['0', '1', '2'], 'PhysicalDrive1': ['0', '1']}
This should work as stated. The value stored in the dictionary is a list - which you can handle as normal.
This, of course, means that you can access the items of the list as:
dict['PhysicalDrive0'][0]
etc.

Your syntax is invalid, the value half of your key-value needs to be a single item, it can be a list, however so you could say 'PhysicalDrive0':['0','1','2']
You would then append to that key-value pair in the dictionary by saying dict['PhysicalDrive0'].append('3')

Related

How to remove and consecutively merge elements in a list [duplicate]

This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 1 year ago.
Let's say we have a list:
listA = ['stack', 'overflow', '1', '2', '3', '4', '1', '5', '3', '7', '2', '3', 'L', '1', ..., 'a', '23', 'Q', '1']
I want to create a new list such as:
new_list = ['1234', '1537', '23L1', ..., 'a23Q1']
So, in this case I want to create a new list using "listA" by removing first two elements and merging all next elements in groups of 4, so the elements: 1, 2, 3, 4; are one element now.
How to approach this in case that I have a very long list to modify. Also, would be nice to know how to approach this problem in case I don't need to create a new list, if all I want is just to modify the list I already have (such as: listA = ['1234', '1537', '23L1', ..., 'a23Q1']). Thanks.
You can create an iterator over that list and then use zip with four identical copies of that iterator to combine each four consecutive elements:
>>> it = iter(listA[2:])
>>> [''.join(x) for x in zip(*[it]*4)]
['1234', '1537', '23L1', 'a23Q1']
itertools.islice allows you to avoid making a temporary copy of that list via slicing:
>>> import itertools
>>> it = itertools.islice(iter(listA), 2, None)
For your specific question, I would just loop through it.
I would do something like this. (Sorry if the format is a bit off this is one of my first answers) This will loop through and combine all complete sets of 4 elements. You could add custom logic if you wanted to keep the end as well. If you don't want to create a new list you can just use "ListA" and ignore the data scrubbing I did by using ListB.
listA = ['stack', 'overflow', '1', '2', '3', '4', '1', '5', '3', '7', '2', '3', 'L', '1', 'a', '23', 'Q', '1']
listB = listA[2:] # remove first two elements
partialList = []
wholeList = []
position = 0
for element in listB:
if position < 4:
partialList.append(element)
position+=1
else:
wholeList.append(''.join(partialList))
position = 0
partialList = []
partialList.append(element)
print(wholeList)
If you don't need a new list you could just create one then set the old list to equal it afterwards. You could try this iterative approach:
listA = ['stack', 'overflow', '1', '2', '3', '4', '1', '5', '3', '7', '2', '3', 'L', '1', 'a', '23']
new_list = [""]
count = 0
for item in listA:
if count % 4 == 0 and count > 0:
new_list.append("")
new_list[-1] += item
count += 1
listA = new_list
print(listA)
Output:
['stackoverflow12', '3415', '3723', 'L1a23']

How to compare each element of multiple lists and return name of lists which are different

I am having multiple lists and I need to compare each list with one another and return the name of lists which are different. We need to consider value of elements in list irrespective of their position while comparing lists.
For example:-
Lis1=['1','2','3']
Lis2=['1','2']
Lis3=['0','1','3']
Lis4=[]
Lis5=['1','2']
Output:-
['Lis1','Lis2','Lis3','Lis4']
Thanks in advance.
Try this:
input_lists = {"Lis1": ['1', '2', '3'], "Lis2": ['1', '2'],
"Lis3": ['0', '1', '3'], "Lis4": [], "Lis5": ['1', '2']}
output_lists = {}
for k, v in input_lists.items():
if sorted(v) not in output_lists.values():
output_lists[k] = sorted(v)
unique_keys = list(output_lists.keys())
print(unique_keys) # ['Lis1', 'Lis2', 'Lis3', 'Lis4']
import itertools
Lis1=['1','2','3']
Lis2=['1','2']
Lis3=['0','1','3']
Lis4=[]
Lis5=['1','2']
k=[Lis1,Lis2,Lis3,Lis4,Lis5]
k.sort()
list(k for k,_ in itertools.groupby(k))
output
[[], ['0', '1', '3'], ['1', '2'], ['1', '2', '3']]
a simple way to implement
Lis1=['1','2','3']
Lis2=['1','2']
Lis3=['0','1','3']
Lis4=[]
Lis5=['1','2']
lis=[Lis1,Lis2,Lis3,Lis4,Lis5]
final=[]
for ele in lis:
if(ele not in final):
final.append(ele)
print(final)
with your given data you can use:
Lis1=['1','2','3']
Lis2=['1','2']
Lis3=['0','1','3']
Lis4=[]
Lis5=['1','2']
name_lis = {'Lis1': Lis1, 'Lis2': Lis2, 'Lis3': Lis3, 'Lis4': Lis4, 'Lis5': Lis5}
tmp = set()
response = []
for k, v in name_lis.items():
s = ''.join(sorted(v))
if s not in tmp:
tmp.add(s)
response.append(k)
print(response)
output:
['Lis1', 'Lis2', 'Lis3', 'Lis4']
name_lis dictionary contains the name of your list and the actual list, you are iterating over each list, and for each list, you are sorting the elements and then converting in a string, if the string was encountered before you know that the list is a duplicate if not you are adding the list to the response

Add values stored in a dictionary as a list of values

I've been searching online for a solution, but everything I've done hasn't been working so far. As the title says, I have a dictionary with a list of values stored in it. I need to add those values together. How would I go about doing that? There are about 1000+ keys and values in the dictionary too, this is just a small example.
{'10_Principles_of_Economics': ['13', '13'],'Advanced_ANOVA': ['2', '1', '1', '2'], 'Advanced_Classical_Mechanics': ['1', '1', '1', '1', '1', '1'], 'Agile_software_development': ['1', '2']}
This is what I tried:
def convert_to_dict(matches):
dictionary = dict()
[dictionary[t[0]].append(t[1]) if t[0] in (dictionary.keys())
else dictionary.update({t[0]: [t[1]]}) for t in matches]
print(dictionary)
return dictionary
def sum_dictionary(dictionary):
dd3 = {}
for key in dictionary:
dd3[key] = [sum(dictionary[key])]
I know there is something wrong here, but I'm not completely sure what. Any help would be appreciated.
This should do:
dd4 = {k:sum([int(v) for v in val]) for k,val in dd3.items()}
Output:
{'10_Principles_of_Economics': 26,
'Advanced_ANOVA': 6,
'Advanced_Classical_Mechanics': 6,
'Agile_software_development': 3}
Your final function would look like this:
def sum_dictionary(dictionary):
return {k:sum([int(v) for v in val]) for k,val in dictionary.items()}
Please tell me if there's something you don't understand. Be careful to use the same variables in your function definition as the ones inside it.
If you want the sum on a list as strings (as stated in your comment), just change this:
{k:[str(sum([int(v) for v in val]))] for k,val in d.items()}
Output 2:
{'10_Principles_of_Economics': ['26'],
'Advanced_ANOVA': ['6'],
'Advanced_Classical_Mechanics': ['6'],
'Agile_software_development': ['3']}
somethig like this:
d = {
'10_Principles_of_Economics': ['13', '13'],
'Advanced_ANOVA': ['2', '1', '1', '2'],
'Advanced_Classical_Mechanics': ['1', '1', '1', '1', '1', '1'],
'Agile_software_development': ['1', '2']
}
Python 3.x
for key, value in d.items():
d[key] = [str(sum([int(x) for x in value]))]
print (d)
Python 2.x
for key, value in d.iteritems():

Replacing a specific index value in list of lists with corresponding dictionary value

I am trying to replace a value in a list of lists (in all relevant sublists) with a VALUE from a dictionary and cannot quite get it to work.
The content/details of the dictionary is as follows:
dictionary = dict(zip(gtincodes, currentstockvalues))
The dictionary contains pairs of GTIN codes and currentstock values. So, 12121212(GTIN)corresponding to value (currentstockvalue) 1, and 12345670 corresponding to value (currentstockvalue) 0.
I now need to look up a list NEWDETAILS which has been read in from file. The list is essentially a list of lists. When newdetails (the list) is printed the output is:
[['12345670', 'Iphone 9.0', '500', '5', '3', '5'], ['12121212', 'Samsung Laptop', '900', '5', '3', '5']]
WHAT NEEDS TO BE DONE:
I would like to use the dictionary to update and replace values in the list (and all relevant sublists in the list). So, for each GTIN (key) in the dictionary, the 3rd index in each sublist (for the corresponding GTIN) needs to be updated with the VALUE (currentstockvalue) in the dictionary.
In the above example, for sublist 1-index[03] of the sublist (whcih is currently 5) needs to be updated with say 2...(or whatever is the value in the dictionary for that GTIN). The same needs to happen for the second sublist.
The code I have so far is:
for sub_list in newdetails:
sub_list[3] = dictionary.get(sub_list[3], sub_list[3])
print(sub_list)
The above simply appears to produce two seperate sublists and print them. It is not making the replacement.
['12345670', 'Iphone 9.0', '500', '5', '3', '5']
['12121212', 'Samsung Laptop', '900', '5', '3', '5']
My question is:
How do I amend the above code to LOOK UP THE DICTIONARY (to match the index[0]) of each sublist, and REPLACE the 4th element(index[03]) of each sublist with the VALUE in the dictionary for the corresponding GTIN?
Thanks in advance.
UPDATE
Based on Alex P's suggestion (thank you) I made the following edit:
for sub_list in newdetails:
sub_list[3] = dictionary.get(gtin), sub_list[3]
print(sub_list)
It comes up with a replacement (of a tuple) rather than just the individual value - as follows:
['12345670', 'Iphone 9.0', '500', (1, '5'), '3', '5']
['12121212', 'Samsung Laptop', '900', (1, '5'), '3', '5']
The contents of the dictionary:
12121212 3
0 0
12345670 1
12121212 is the gtin and '3' is the current stock.
I want to look up the dictionary, IF a corresponding GTIN is found in the newdetails list, I want to replace the third index (fourth element) in the newdetails list, with the corresponding value in the dictionary. So - for 12121212, 5 to be replaced with 3. And for 12345670, 5 to be replaced with 1.
UPDATE based on suggestion by Moses K
I tried this - thank you - but ....
for sub_list in newdetails:
sub_list[3] = dictionary.get(int(sub_list[0]), sub_list[3])
print(sub_list)
the output is still simply the two (unchanged) sublists.
['12345670', 'Iphone 9.0', '500', '5', '3', '5']
['12121212', 'Samsung Laptop', '900', '5', '3', '5']
Update #2 - both converted to int.
for sub_list in newdetails:
print("sublist3")
print(sub_list[3])
sub_list[3] = dictionary.get(int(sub_list[0]), (int(sub_list[3])))
print(sub_list)
Still producing an output of:
['12345670', 'Iphone 9.0', '500', 5, '3', '5']
['12121212', 'Samsung Laptop', '900', 5, '3', '5']
instead of (what I want)that is:
['12345670', 'Iphone 9.0', '500',2, '3', '5']
['12121212', 'Samsung Laptop', '900', 1, '3', '5']
Your GTIN code at index 0 of each sublist should be your dictionary key:
for sub_list in newdetails:
sub_list[3] = dictionary.get(sub_list[0], sub_list[3])
# ^
If the codes in the dictionary are integers and not strings then you'll need to cast them to int:
for sub_list in newdetails:
sub_list[3] = dictionary.get(int(sub_list[0]), sub_list[3])
# ^

How to perform an operation on all values of a 2D list in Python

I've got a list like so:
counters = [["0"],["0"],["0"],["0"]]
I'd like to perform an operation to each of the inner values - say concatenation, converting to an int and incrementing, etc.
How can I do this for all of the list items; given that this is a multi-dimensional list?
You can use list comprehension (nested list comprehension):
>>> counters = [["0"],["0"],["0"],["0"]]
>>> [[str(int(c)+1) for c in cs] for cs in counters]
[['1'], ['1'], ['1'], ['1']]
BTW, why do you use lists of strings?
I'd rather use a list of numbers (No need to convert to int, back to str).
>>> counters = [0, 0, 0, 0]
>>> [c+1 for c in counters]
[1, 1, 1, 1]
>>> counter=['0']*10
>>> counter
['0', '0', '0', '0', '0', '0', '0', '0', '0', '0']
>>> counter=['1']*10
>>> counter
['1', '1', '1', '1', '1', '1', '1', '1', '1', '1']
overwrite a counter with 1,s
>>> counters = [["0"],["0"],["0"],["0"]]
>>> counters = [ [str(eval(i[0])+1)] for element in counters ]
>>> counters
[['1'], ['1'], ['1'], ['1']]
We can use eval function here. About eval() What does Python's eval() do?
If list comprehension scares you, you can use sub-indexing. For example,
for i in range(len(counters)):
counters[i][0] = str(eval(counters[i][0]) + 1)
counters is a list of lists, therefore you need to access the subindex of 0 (the first item) before you add to it. counters[0][0], for example, is the first item in the first sublist.
Moreover, each of your subitems is a string, not an integer or float. The eval function makes the proper conversion so that we can add 1, and the outer str function converts the final answer back to a string.

Categories

Resources