How to convert string to dictionary into python - python

How can I convert a string
s = "1:5.9,1p5:7,2:10,4:18,8:40"
to a dictionary like this?
s = { '1':'5.9','1p5':'7','2':'10','4':'18','8':40'}

Use dict() and str.split:
>>> s = "1:5.9,1p5:7,2:10,4:18,8:40"
>>> dict(item.split(':') for item in s.split(','))
{'1': '5.9', '8': '40', '2': '10', '4': '18', '1p5': '7'}
Using a dict-comprehension:
>>> {k:v for k, v in (item.split(':') for item in s.split(','))}
{'1': '5.9', '8': '40', '2': '10', '4': '18', '1p5': '7'}

Related

How to get the keys if one of key is or '0' in dictionary

I have Dictionary is below, My product output is below. I need to create a new dictionary with two types Out_1, Out_2
product = {'Product1': {'index': '1', '1': 'Book', '2': 'Pencil', '3': 'Pen','value': '1'},
'Product2': {'index': '2', '1': 'Marker', '2': 'MYSQL', '3': 'Scale','value': '0'}}
If value inside product is 0 then extract the keys
Expected Output
Out_1 = {'Product2': {1:'Marker': '2': 'Compass', '3': 'Scale', 'value': 0}}
Out_2 = {'Product2':['Marker','Compass','Scale', '0']}
Psuedo code is below. i tried to create but not able to create as above
Out_1 = {}
Out_2 = {i:[]}
for i,j in product.items():
for a,b in j.items():
if a['value'] == 0:
Out_2.append(i)
I am getting indices error, How to get Out_1, Out_2
You can use dict comprehensions for this.
out_1 = {k: v for k, v in product.items() if v['value']=='0'}
out_2 = {k: list(v.values()) for k, v in product.items() if v['value']=='0'}
Hi do you really need this index variable? If not yes why would not you use list of dicts instead of dict of dicts. However here is what you wanted:
products = {'Product1': {'index': '1', '1': 'Book', '2': 'Pencil', '3': 'Pen','value': '1'},
'Product2': {'index': '2', '1': 'Marker', '2': 'MYSQL', '3': 'Scale','value': '0'}}
for k,product in products.items():
product.pop('index', None)
if product['value'] == '0':
products[k] = list(product.values())
print(products)
>>> {'Product1': {'1': 'Book', '2': 'Pencil', '3': 'Pen', 'value': '1'}, 'Product2': ['Marker', 'MYSQL', 'Scale', '0']}
I was not assigning it to any other variables like out1/2 in case you have more than 2 products
Here it is:
Code:
product = {'Product1': {'index': '1', '1': 'Book', '2': 'Pencil', '3': 'Pen','value': '1'},
'Product2': {'index': '2', '1': 'Marker', '2': 'MYSQL', '3': 'Scale','value': '0'}}
output_1 = {}
output_2 = {}
for key,val in product.items():
if (val['value'] == '0'):
output_1[key]=val
output_2[key]=val.values()
print(output_1)
print(output_2)
Output:
{'Product2': {'1': 'Marker', 'index': '2', '3': 'Scale', '2': 'MYSQL', 'value': '0'}}
{'Product2': ['Marker', '2', 'Scale', 'MYSQL', '0']}

group dict emelents on lists based on key name

I want to group dict keys in list of dicts based on dict keys name. The dict keys alawys starts with number for example :
{'1_account_id': '5', '1_qty_in': '10.01', '1_uom_in': '1', '2_account_id': '23', '2_qty_in': '2.01', '2_uom_in': '1','3_account_id': '23', '3_qty_in': '2.01', '3_uom_in': '1' ,'some_x':1,'some_y':0}
I want to convert that to list grouped by this number like:
[{'1':{account_id': '5','qty_in':10.01,'uom_in':1}},{'2':{account_id': '23','qty_in':2.01,'uom_in':1}}....] etc
This numbers is not static.
I tried multiple solutions but it seems not good for performace:
Like i looped range for 0 to SOMEBIGNUMBER but this is not a good solution.
i also tried to loop throw the elements to extract the numbers first and then loop again to group but the dict myaybe come not clean as it has other not needed keys.
What should i do ?
So given the input d
d = {'1_account_id': '5', '1_qty_in': '10.01', '1_uom_in': '1', '2_account_id': '23', '2_qty_in': '2.01', '2_uom_in': '1','3_account_id': '23', '3_qty_in': '2.01', '3_uom_in': '1' ,'some_x':1,'some_y':0}
ans = {}
for key in d:
n,k = key.split('_', 1)
if n in ans:
ans[n][k] = d[key]
else:
ans[n] = {'account_id': 0, 'qty_in': 0, 'uom_in': 0}
ans[n][k] = d[key]
The above code produces the following output in which the entire output ans is a dictionary with the numbers as keys, and the values for each of the keys is also a dictionary, each containing 3 keys and corresponding values :
{'1': {'account_id': '5', 'qty_in': '10.01', 'uom_in': '1'},
'2': {'account_id': '23', 'qty_in': '2.01', 'uom_in': '1'},
'3': {'account_id': '23', 'qty_in': '2.01', 'uom_in': '1'},
'some': {'account_id': 0, 'qty_in': 0, 'uom_in': 0, 'x': 1, 'y': 0}}
Now to convert it into the list which you have shown in the desired output, use the follwing code. Here we convert the dictionary of dictionaries to a list containing dictionaries.
ans2 = []
for row in ans:
temp = {}
temp[row] = ans[row]
ans2.append(temp)
which produces the desired output :
[{'1': {'account_id': '5', 'qty_in': '10.01', 'uom_in': '1'}},
{'2': {'account_id': '23', 'qty_in': '2.01', 'uom_in': '1'}},
{'3': {'account_id': '23', 'qty_in': '2.01', 'uom_in': '1'}},
{'some': {'account_id': 0, 'qty_in': 0, 'uom_in': 0, 'x': 1, 'y': 0}}]
Hope this helps !
Mostafa.
You can run this code example to solve it:
example_dict = {'1_account_id': '5', '1_qty_in': '10.01', '1_uom_in': '1', '2_account_id': '23', '2_qty_in': '2.01', '2_uom_in': '1','3_account_id': '23', '3_qty_in': '2.01', '3_uom_in': '1' ,'some_x':1,'some_y':0}
desired_keys = ['account_id','qty_in','uom_in']
result = {}
for key,value in example_dict.items():
key_num, key_name = key.split('_', 1)
if key_name in desired_keys:
result.setdefault(key_num, {})[key_name] = value
print(result)
{'1': {'accountid': '5', 'qtyin': '10.01', 'uomin': '1'}, '2': {'accountid': '23', 'qtyin': '2.01', 'uomin': '1'}, '3': {'accountid': '23', 'qtyin': '2.01', 'uomin': '1'}, 'some': {'x': 1, 'y': 0}}
It will print (as you desired):
{'1': {'accountid': '5', 'qtyin': '10.01', 'uomin': '1'}, '2': {'accountid': '23', 'qtyin': '2.01', 'uomin': '1'}, '3': {'accountid': '23', 'qtyin': '2.01', 'uomin': '1'}, 'some': {'x': 1, 'y': 0}}
Tell me if you do not understand something.

Python 3 Dictionary sorted with wrong output

I am currently doing an Assignment; however, I got some interesting output which confused me so much.
I am trying to sort the following dictionary:
result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}
My sorting code with Python 3 is the following : (only sorted by value)
sortedList = [v for v in sorted(result.values())]
The output is :
['0', '10', '10', '14', '16', '171', '19', '22', '267', '34', '407', '47', '53', '56', '75', '9']
which is not fully sorted. The output is quite strange.
Why it is happened like this?
I have used another dict to test like this:
testD = {'A':'5','B': '9','c': '8','d': '6'}
the output is right :
['5', '6', '8', '9']
Is there something wrong with my result dictionary or is there something I am missing?
Strings will be ordered with a lexical sort. To sort your data numerically, convert the values into integers first.
Strings are compared one character at a time, so '30' < '4' because '3' < '4'. You need to use a key parameter to get the comparison based on the numeric value, not the string characters.
Also, it's redundant to use a list comprehension on something that already returns a list.
sortedList = sorted(result.values(), key=int)
As the value of dictionary are string so there is lexical sorting based on ascii values.
As evident, you need the values to be sorted according to their integer values.
result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}
As mentioned in the comments by #AChampion, you can pass the sort value type by using key something like this :
sortedList = sorted(result.values(), key = int)
print(sortedList)
Or you can do something like this :
result_ints = dict((k,int(v)) for k,v in result.items())
sortedList = [str(v) for v in sorted(result_ints.values())]
print(sortedList)
Both of the above code snippets will result in :
['0', '9', '10', '10', '14', '16', '19', '22', '34', '47', '53', '56', '75', '171', '267', '407']
You can try this :
result = [{'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}]
lst=[]
for item in result:
for key in item.keys():
lst.append(int(item.get(key)))
sortedList = [v for v in sorted(lst)]
print(sortedList)
Output: [0, 9, 10, 10, 14, 16, 19, 22, 34, 47, 53, 56, 75, 171, 267,
407]

Merge two equal-length lists into a dictionary, mapping one-to-many

I have two lists with an equal number of elements. The position of each element corresponds between the lists. One of lists has repeated elements while the other does not.
How can I create a dictionary from the two lists where a key from Lst1 can be mapped to multiple values in Lst2?
Lst1 = ['11', '13', '11', '12', '11', '13', '12', '12', '12', '13', '11']
Lst2 = ['1/41', '1/34', '1/37', '1/47', '1/41', '1/33', '1/46', '1/45', 'p4', 'p5', 'p6']
result:
Dict1 = {'11': ['1/41', '1/37', '1/141', 'p6'],
'12': ['1/47', '1/33', '1/46', 'p4'],
'13': ['1/34', '1/33', 'p5']}
from the two list- wanting to create Dict1.
Zip the two lists together and gather repeating values in a list in a new dictionary:
Dict1 = {}
for key, val in zip(Lst1, Lst2):
Dict1.setdefault(key, []).append(val)
Demo:
>>> Lst1 = ['11', '13', '11', '12', '11', '13', '12', '12', '12', '13', '11']
>>> Lst2 = ['1/41', '1/34', '1/37', '1/47', '1/41', '1/33', '1/46', '1/45', 'p4', 'p5', 'p6']
>>> Dict1 = {}
>>> for key, val in zip(Lst1, Lst2):
... Dict1.setdefault(key, []).append(val)
...
>>> Dict1
{'11': ['1/41', '1/37', '1/41', 'p6'], '13': ['1/34', '1/33', 'p5'], '12': ['1/47', '1/46', '1/45', 'p4']}
>>> from pprint import pprint
>>> pprint(Dict1)
{'11': ['1/41', '1/37', '1/41', 'p6'],
'12': ['1/47', '1/46', '1/45', 'p4'],
'13': ['1/34', '1/33', 'p5']}

create a Python dictionary when reading a file

I have a list derived from a text file (filename) with an header
mylist = [l.split() for l in open(filename, "r")]
mylist = [['A','B','C','D'],['1','2','3','4'],['10','20','30','40'],['100','200','300','400']]
i wish to create a dictionary directly reading the file in order to save lines of code as:
mtlist_dist = {A: ['1','10','100'], B: [''2,'20','200'], C: ['3','30','300'], D: ['4','40','400']}
You can do this easily with zip and a dictionary comprehension:
>>> mylist = [['A','B','C','D'],['1','2','3','4'],['10','20','30','40'],['100','200','300','400']]
>>> {x[0]:x[1:] for x in zip(*mylist)}
{'A': ('1', '10', '100'), 'C': ('3', '30', '300'), 'B': ('2', '20', '200'), 'D': ('4', '40', '400')}
>>> {x[0]:list(x[1:]) for x in zip(*mylist)}
{'A': ['1', '10', '100'], 'C': ['3', '30', '300'], 'B': ['2', '20', '200'], 'D': ['4', '40', '400']}
>>>
In Python 3.x, the solution becomes even more concise with extended iterable unpacking:
>>> mylist = [['A','B','C','D'],['1','2','3','4'],['10','20','30','40'],['100','200','300','400']]
>>> {x:y for x,*y in zip(*mylist)}
{'D': ['4', '40', '400'], 'A': ['1', '10', '100'], 'C': ['3', '30', '300'], 'B': ['2', '20', '200']}
>>>
You can do it as:
my_dict = dict(zip(mylist[0], zip(*mylist[1:])))
>>> print my_dict
{'A': ('1', '10', '100'), 'C': ('3', '30', '300'), 'B': ('2', '20', '200'), 'D': ('4', '40', '400')

Categories

Resources