Multiplying the values of dictionaries with different keys - python

The problem of multiplying of values of two dictionaries with the same keys, I decided as follows:
v1={'name1': '10', 'name2': '20'}
v2={'name1': '4', 'name2': '5'}
foo = lambda dct_1, dct_2: {key: int(dct_2[key]) * int(dct_1[key]) for key in dct_2}
foo(v1, v2)
# Out: {'name1': 40, 'name2': 100}
How can I multiply values of two dictionaries in the same way, but with the different keys ?
v1={'name1': '10', 'name2': '20'}
v2={'quantity1': '4', 'quantity2': '5'}
#OUT: {'name1':'40', 'name2': '100'}

Assuming you always have corresponding nameX and quantityX values, you could use a simple replace on the keys:
foo = lambda dct_1, dct_2: {key: int(dct_2[key.replace('name', 'quantity')]) * int(dct_1[key]) for key in dct_1}

multiplydicts = lambda x,y: { key: str(int(v1[key]) * int(val)) for key,val in zip(v1.keys(), v2.values())}
Assuming that your dictionaries are the same size this should do the trick, and v2.values() will return the values of v2 in order of construction.

you can do :
>>> v1={'name1': '10', 'name2': '20'}
>>> v2={'quantity1': '4', 'quantity2': '5'}
>>> d={'name'+str(i+1) : int(v1['name'+str(i+1)])*int(v2['quantity'+str(i+1)]) for i in range(len(v1))}
>>> d
{'name2': 100, 'name1': 40}

You just need to add something to map the keys in the first dictionary to those in second. The easiest way to do it is with a third dictionary named keymap in the code below. The keys in the first dictionary determine the ones that will appear in the one returned.
This is needed because the order of keys in ordinary dictionaries is undefined, so you can't rely or predict what order they will appear in when you iterate over them.
v1={'name1': '10', 'name2': '20'}
v2={'quantity1': '4', 'quantity2': '5'}
keymap = {'name1': 'quantity1', 'name2': 'quantity2'} # Added.
foo = (lambda dct_1, dct_2:
{key: int(dct_2[keymap[key]]) * int(dct_1[key]) for key in dct_1})
print(foo(v1, v2)) # -> {'name1': 40, 'name2': 100}

Related

Make a list consistent

I have 2 list ..
a = [{'Work': 'R'}, {'Area': 'S0'}, {'Type': 'PIV'}, {'Disc': 'LA'}, {'L': 'A'}]
b = [{'Key': '9', 'FileName': '123A.pdf', 'Code': '1', 'Type': 'PNHRG'}]
output -- [{'Key': '9', 'FileName': '123A.pdf', 'Code': '1', 'Type': 'PNHRG','Work': 'R','Area': 'S0','Type': 'PIV','Disc': 'LA','L': 'A'}]
I tried 'extend','append','insert' but did not get desired
output. tried all most all list operations with loops too. I am
not in position to change any kind of types for this.
Tried this solution too without luck. not sure where I am missing.
How do I make a flat list out of a list of lists?
You can use a doubly-nested dictionary comprehension, iterating over all the items in all the dicts in all the lists. Assuming multiple dicts in b might not be necessary, but makes it easier.
>>> a = [{'Work': 'R'}, {'Area': 'S0'}, {'Type': 'PIV'}, {'Disc': 'LA'}, {'L': 'A'}]
>>> b = [{'Key': '9', 'FileName': '123A.pdf', 'Code': '1', 'Type': 'PNHRG'}]
>>> [{k: v for lst in (a, b) for d in lst for k, v in d.items()}]
[{'Work': 'R', 'Area': 'S0', 'Type': 'PNHRG', 'Disc': 'LA', 'L': 'A', 'Key': '9', 'FileName': '123A.pdf', 'Code': '1'}]
Addendum: If there are any keys that appear in more than one dictionary, as is the case with "type" here, the value from the last dictionary that was iterated in the comprehension will be used, i.e. b here. If you need the value from a, do ... for lst in (b, a).... In your expected output, that key appears twice, but that is not possible unless you change the format, as in the other answer.
Extra from the answer provided by tobias_k:
If you want to combine both lists of dictionaries (and more when you have it) as a dictionary with a list of values in the same key. You can do this.
from collections import defaultdict
mydict = defaultdict(list)
for i in (a+b):
for key, value in i.items():
mydict[key].append(value)
mydict
Out[32]:
defaultdict(list,
{'Work': ['R'],
'Area': ['S0'],
'Type': ['PIV', 'PNHRG'],
'Disc': ['LA'],
'L': ['A'],
'Key': ['9'],
'FileName': ['123A.pdf'],
'Code': ['1']})

Convert values from list of dictionaries from string to integer

I have a list of 54 dictionaries, formatted as so:
[{'1A': '1',
'3E': '2',
'PRODUCT NUMBER': '1',
'Week': '1'}
,
{'1A': '1',
'1B': '1',
'1C': '1',
'1D': '2',
'1E': '2',
'2C': '1',
'3E': '2',
'PRODUCT NUMBER': '2',
'Week': '1'},...] and etc
I am trying to convert the values from strings to integers.
I have successfully managed to do this for my very last dictionary, but it doesnt seem to be working for the rest.
This is my code:
for i in buyers: #buyers is the list
for n in buyers_dict: # the code works without this line the same, i cant figure out where to implement the 'n'
for k, v in buyers_list.items():
buyers_list[k] = int(v)
pprint.pprint(buyers)
Like I said, the 54th dictionary values are converted, but the rest are still strings
here is my excel file:
I've then condensed the dictionaries to just contain the key values pairs that have a value. Now I need to convert the values into integers.
Assuming your data is in this schema:
buyers = [{...}, {...}, ...]
You need to loop through the list of dicts then work on those dicts in particular:
for d in buyers:
for k, v in d.items():
d[k] = int(v)
Or in comprehension form:
buyers = [{k: int(v) for k, v in d.items()} for d in buyers]
d=[{'1A': '1',
'3E': '2',
'PRODUCT NUMBER': '1',
'Week': '1'}]
Using Comprehension
[{k:int(v)} for i in d for (k,v) in i.items() ]
Output:
[{'1A': 1}, {'3E': 2}, {'PRODUCT NUMBER': 1}, {'Week': 1}]

Is it possible to write a function that returns multiple values in a specific format?

I'm writing a function that returns two values which will form the key-value pair of a dictionary. This function will be used to create a dictionary with dictionary comprehension. However, using dictionary comprehension the pair of values need to be provided in the format 'key: value'. To accomplish this, I have to call the function twice. Once for the key, and once for the value. For example,
sample_list = [['John', '24', 'M', 'English'],
['Jeanne', '21', 'F', 'French'],
['Yuhanna', '22', 'M', 'Arabic']]
def key_value_creator(sample_list):
key = sample_list[0]
value = {'age': sample_list[1],
'gender': sample_list[2],
'lang': sample_list[3]}
return key, value
dictionary = {key_value_creator(item)[0]: \
key_value_creator(item)[1] for item in sample_list}
As you can see, the function is called twice to generate values that can be generated in one run. Is there a way to return the values in a format that can be usable by the comprehension? If that is possible, the function need only be called once, as such:
dictionary = {key_value_creator(item) for item in sample_list}
As far as I have seen, other ways of returning multiple values is to return them in the form of a dictionary or list,
return {'key': key, 'value': value}
return [key, value]
but either way, to access them we will have to call the function twice.
dictionary = {key_value_creator(item)['key']: \
key_value_creator(item)['value'] for item in sample_list}
dictionary = {key_value_creator(item)[0]: \
key_value_creator(item)[1] for item in sample_list}
Is there a way to format these values so that we can send them to the dictionary comprehension statement in the format that it requires?
EDIT:
Expected Output:
{ 'John': {'age': '24', 'gender': 'M', 'lang': 'English'},
'Jeanne': {'age': '21', 'gender': 'F', 'lang': 'French'},
'Yuhanna': {'age': '22', 'gender': 'M', 'lang': 'Arabic'}}
Just use the dict builtin function, expecting a sequence of (key, value) pairs as returned by your key_value_creator function and making a dict from those:
>>> dict(map(key_value_creator, sample_list))
{'Jeanne': {'age': '21', 'gender': 'F', 'lang': 'French'},
'John': {'age': '24', 'gender': 'M', 'lang': 'English'},
'Yuhanna': {'age': '22', 'gender': 'M', 'lang': 'Arabic'}}
Also works with a generator expression instead of map:
>>> dict(key_value_creator(item) for item in sample_list)
Or use a dictionary comprehension with a nested generator expression and tuple-unpacking:
>>> {k: v for k, v in (key_value_creator(item) for item in sample_list)}
Or without your key_value_creator function, just using a nested dictionary comprehension:
>>> {n: {"age": a, "gender": g, "lang": l} for n, a, g, l in sample_list}

How to merge data from multiple dictionaries with repeating keys?

I have two dictionaries:
dict1 = {'a': '2', 'b': '10'}
dict2 = {'a': '25', 'b': '7'}
I need to save all the values for same key in a new dictionary.
The best i can do so far is: defaultdict(<class 'list'>, {'a': ['2', '25'], 'b': ['10', '7']})
dd = defaultdict(list)
for d in (dict1, dict2):
for key, value in d.items():
dd[key].append(value)
print(dd)
that does not fully resolve the problem since a desirable result is:
a = {'dict1':'2', 'dict2':'25'}
b = {'dict2':'10', 'dict2':'7'}
Also i possibly would like to use new dictionary key same as initial dictionary name
Your main problem is that you're trying to cross the implementation boundary between a string value and a variable name. This is almost always bad design. Instead, start with all of your labels as string data:
table = {
"dict1": {'a': '2', 'b': '10'},
"dict2": {'a': '25', 'b': '7'}
}
... or, in terms of your original post:
table = {
"dict1": dict1,
"dict2": dict2
}
From here, you should be able to invert the levels to obtain
invert = {
"a": {'dict1': '2', 'dict2': '25'},
"b": {'dict2': '10', 'dict2': '7'}
}
Is that enough to get your processing where it needs to be? Keeping the data in comprehensive dicts like this, will make it easier to iterate through the sub-dicts as needed.
As #Prune suggested, structuring your result as a nested dictionary will be easier:
{'a': {'dict1': '2', 'dict2': '25'}, 'b': {'dict1': '10', 'dict2': '7'}}
Which could be achieved with a dict comprehension:
{k: {"dict%d" % i: v2 for i, v2 in enumerate(v1, start=1)} for k, v1 in dd.items()}
If you prefer doing it without a comprehension, you could do this instead:
result = {}
for k, v1 in dd.items():
inner_dict = {}
for i, v2 in enumerate(v1, start=1):
inner_dict["dict%d" % i] = v2
result[k] = inner_dict
Note: This assumes you want to always want to keep the "dict1", "dict2",... key structure.

Accesssing all values from same key for different dictionaries within nested dictionary

I have a nested dictionary:
d = { 'wing': {'name': 'Ali', 'age': '19'},
'scrumHalf': {'name': 'Bob', 'age': '25'},
'flyHalf': {'name': 'Sam', 'age': '43'},
'prop': {'name': 'rob', 'age': '33'}}
I want to pull out the values for age only to generate a list
[19, 25, 43, 33]
I want to do this using a for loop, and as naively as possible, as I usually find that easiest to understand.
I have managed to print all of the keys using a for loop:
for i in d:
print i
for j in d[i]:
print j
but when I tried to edit it to print the values I got the error
NameError: name 'value' is not defined. How can I get 'value' to mean the value attached to a key?
Here is my edited version
for i in d:
print (i[value])
for j in d[i]:
print (j[value])
I am using python 2.7
You can access values in the dict with the help of the method values():
[i['age'] for i in d.values()]
# ['19', '25', '43', '33']
>>> [d.get(k).get('age') for k, v in d.items()]
['33', '25', '19', '43']
In-order to access a dictionary's value you are iterating through keys first which is correct i.e. for i in d:. So, in order to access value of key i in d, you'll need to do d[i] which will give you the value, for example {'name': 'rob', 'age': '33'} then to access the required key you'll have to access from dictionary once more i.e. d[i]['age'].

Categories

Resources