Related
I have the following data
data={
None: [
{'ne': '1', 'na': '1'},
{'ne': '2', 'na': '2'},
{'ne': '3', 'na': '3'},
{'ne': '4', 'na': '4'}
],
'AO': [
{'ne': '2', 'na': '2'},
{'ne': '6', 'na': '6'}
],
'NZ': [
{'ne': '1', 'na': '1'}
]
}
and I want to have a list from it like this:
[
{'ne': '1', 'na': '1', 'country': [None, 'NZ']},
{'ne': '2', 'na': '2', 'country': [None, 'AO']},
{'ne': '3', 'na': '3', 'country': [None]},
{'ne': '4', 'na': '4', 'country': [None]},
{'ne': '6', 'na': '6', 'country': ['AO']}
]
my code is doing it fine but it's far from being "pythonic" because I'm a newbie at python:
data = {None: [{'ne': '1', 'na': '1'}, {'ne': '2', 'na': '2'}, {'ne': '3', 'na': '3'}, {'ne': '4', 'na': '4'}], 'AO': [{'ne': '2', 'na': '2'}, {'ne': '6', 'na': '6'}], 'NZ': [{'ne': '1', 'na': '1'}]}
data_list = []
for k,d in data.items():
for dd in d:
dd['country'] = k
data_list.append(dd)
help_dict = {}
for item in data_list:
help_dict[item['ne']] = False
final_list = []
for idx, val in enumerate(data_list):
if not help_dict[val['ne']]:
val['country'] = [val['country']]
for idx2, val2 in enumerate(data_list):
if idx2 != idx and val['ne'] == val2['ne']:
val['country'].append(val2['country'])
help_dict[val['ne']] = True
final_list.append(val)
print(final_list)
can someone help me with a better way to do this?
new = [x for key,value in data.items() for x in value]
# remove duplicate dictionaries
new = [dict(t) for t in {tuple(d.items()) for d in new}]
for d in new:
d['country'] = [key for key,data in data.items() if d in data]
print(new)
>>> [{'ne': '2', 'na': '2', 'country': [None, 'AO']},
{'ne': '4', 'na': '4', 'country': [None]},
{'ne': '1', 'na': '1', 'country': [None, 'NZ']},
{'ne': '6', 'na': '6', 'country': ['AO']},
{'ne': '3', 'na': '3', 'country': [None]}]
If you want to preserve the order
new = [x for n,(key,value) in enumerate(data.items()) for x in value]
seen = set()
new_l = []
for d in new:
t = tuple(d.items())
if t not in seen:
seen.add(t)
new_l.append(d)
for d in new_l:
d['country'] = [key for key,data in data.items() if d in data]
print(new_l)
>>> [{'ne': '1', 'na': '1', 'country': [None, 'NZ']},
{'ne': '2', 'na': '2', 'country': [None, 'AO']},
{'ne': '3', 'na': '3', 'country': [None]},
{'ne': '4', 'na': '4', 'country': [None]},
{'ne': '6', 'na': '6', 'country': ['AO']}]
This is a really naive approach to solve your problem, due to it requiring that the inner dictionaries are sorted in the same order for it to "match" earlier found dictionaries.
For more complex dictionaries inside of the country this might not give correct results:
data={
None: [
{'ne': '1', 'na': '1'},
{'ne': '2', 'na': '2'},
{'ne': '3', 'na': '3'},
{'ne': '4', 'na': '4'}
],
'AO': [
{'ne': '2', 'na': '2'},
{'ne': '6', 'na': '6'}
],
'NZ': [
{'ne': '1', 'na': '1'}
]
}
d = {}
for country in data:
for dictionary in data[country]:
# Create a key that is a string of the dictionary, and value is dictionary plus country
x = d.setdefault(str(dictionary), dictionary | {"country": []})
# If you're using Python < 3.9, use this instead:
# x = d.setdefault(str(dictionary), {**dictionary, "country": []})
x["country"].append(country)
# pprint only used to represent data better
import pprint
pprint.pp(list(d.values()))
Output:
[{'ne': '1', 'na': '1', 'country': [None, 'NZ']},
{'ne': '2', 'na': '2', 'country': [None, 'AO']},
{'ne': '3', 'na': '3', 'country': [None]},
{'ne': '4', 'na': '4', 'country': [None]},
{'ne': '6', 'na': '6', 'country': ['AO']}]
Firstly, I'm assuming ne and na are always the same.
An optimal intermediate data structure is a dict with ne/na as keys and country lists as values:
{'1': [None, 'NZ'],
'2': [None, 'AO'],
'3': [None],
'4': [None],
'6': ['AO']}
Once you have that goal in mind, it's super simple to do it Pythonically:
inter = {}
for k, dicts in data.items():
for d in dicts:
inter.setdefault(d['ne'], []).append(k)
dict.setdefault() is used to get the value if it exists, or if not, set it to a default, which is an empty list here. It's functionally the same as this:
ne = d['ne']
if ne not in inter:
inter[ne] = []
inter[ne].append(k)
You could also use collections.defaultdict(list) to do the same thing even more easily.
And once you have that dict, you just need to unpack it into a list of dicts:
result = [{'ne': ne, 'na': ne, 'country': c} for ne, c in inter.items()]
Which becomes:
[{'ne': '1', 'na': '1', 'country': [None, 'NZ']},
{'ne': '2', 'na': '2', 'country': [None, 'AO']},
{'ne': '3', 'na': '3', 'country': [None]},
{'ne': '4', 'na': '4', 'country': [None]},
{'ne': '6', 'na': '6', 'country': ['AO']}]
I have the json code below and I have a list
i want to do a for loop or if statement which
if label in selected_size:
fsize = id
selected_size[]
in selected size:
[7, 7.5, 4, 4.5]
in json:
removed
print(json_data)
for size in json_data:
if ['label'] in select_size:
fsize = ['id']
print(fsize)
i have no idea on how to do it.
You need to access to list and later to dict, for example:
json_data = [{'id': '91', 'label': '10.5', 'price': '0', 'oldPrice': '0', 'products': ['81278']}, {'id': '150', 'label': '9.5', 'price': '0', 'oldPrice': '0', 'products': ['81276']}, {'id': '28', 'label': '4', 'price': '0', 'oldPrice': '0', 'products': ['81270']}, {'id': '29', 'label': '5', 'price': '0', 'oldPrice': '0', 'products': ['81271']}, {'id': '22', 'label': '8', 'price': '0', 'oldPrice': '0', 'products': ['81274']}, {'id': '23', 'label': '9', 'price': '0', 'oldPrice': '0', 'products': ['81275']}, {'id': '24', 'label': '10', 'price': '0', 'oldPrice': '0', 'products': ['81277']}, {'id': '25', 'label': '11', 'price': '0', 'oldPrice': '0', 'products': ['81279']}, {'id': '26', 'label': '12', 'price': '0', 'oldPrice': '0', 'products': ['81280']}]
fsize = []
select_size = [7, 7.5, 4, 4.5]
[float(i) for i in select_size] #All select_size values to float value
for size in json_data:
if float(size['label']) in select_size: #For compare it i need float(size['label']) for convert to float.
fsize.append(size['id']) #Add to list
print(fsize) #Print all list, i get only 28
I'm trying to calculate Net run rate for the list containing dictionaries
suppose if list is
score = [{'dismissal': 'run out (Hardik Pandya)', 'balls': '92', 'name': 'Amla', 'fours': '5', 'six': '0', 'runs': '71'}, {'dismissal': 'c Kohli b Bumrah', 'balls': '32', 'name': 'Markram(c)', 'fours': '4', 'six': '1', 'runs': '32'}, {'dismissal': 'c Rohit b Hardik Pandya', 'balls': '5', 'name': 'Duminy', 'fours': '0', 'six': '0', 'runs': '1'}..........]
I'm trying to calculate NRR for these valuese which are dynamic they keep changing, I tried using enumerate but I can't figure out how to proceed further
dic= {k+str(i): v for i, x in enumerate(score, 1) for k, v in x.items()}
this will add indexes to the key of a dictionary how can I proceed after this, is there any other way its possible to achieve this?
By the way, to calculate NRR formula is = (runs/balls)*100, any assistance will be helpful.
expecting to get like this
dic = [{'dismissal1': 'run out (Hardik Pandya)', 'balls1': '92', 'name1': 'Amla', 'fours1': '5', 'six1': '0', 'runs1': '71','NRR1':'19.3'}, {'dismissal2': 'c Kohli b Bumrah', 'balls2': '32', 'name2': 'Markram(c)', 'fours2': '4', 'six2': '1', 'runs2': '32','NRR2':'44.3'}, {'dismissal3': 'c Rohit b Hardik Pandya', 'balls3': '5', 'name3': 'Duminy', 'fours3': '0', 'six3': '0', 'runs3': '1','NRR3':'45.3'}..........]
I have a list of dictionaries -
list1 = [{'id' : '1', 'b' : '2', 'c' : '3'}, {'id' : '4', 'b' : '5', 'c' : '6'}, {'id' : '7', 'b' : '8', 'c' : ''}]
Based on the value of c being null or not, I am making a call which returns -
list2 - {'d' : '30', 'id' : 1}, {'d': '25', 'id' : '4'}
Now I want to modify list1, so that the final list has the values of d for the ids which have c. For example -
list1 = [{'id' : '1', 'b' : '2', 'c' : '3', 'd' : '30'}, {'id' : '4', 'b' : '5', 'c' : '6', 'd' : '25'}, {'id' : '7', 'b' : '8', 'c' : ''}]
My approach -
for l in list2:
current_list = {}
for l2 in list1:
if l2['id'] == l['id']:
current_list = l2
break
if current_list:
current_list['d'] = l['d']
Here the actual dict is not getting modified. How can I modify the actual list? Also, is there a neater way to do this?
I'm not certain I understand what you are trying to accomplish. Your written description of your goal does not agree with you code. Based on the code, I'm guessing that you want to match up the data based on the id values.
# You've got some dicts.
dicts = [
{'id': '1', 'b': '2', 'c': '3'},
{'id': '4', 'b': '5', 'c': '6'},
{'id': '7', 'b': '8', 'c': ''},
]
# You've got some other dicts having the same IDs.
d_dicts = [
{'d': '30', 'id': '1'},
{'d': '25', 'id': '4'},
]
# Reorganize that data into a dict, keyed by ID.
dlookup = {d['id'] : d['d'] for d in d_dicts}
# Now add that lookup data to the main list of dicts.
for d in dicts:
i = d['id']
if i in dlookup:
d['d'] = dlookup[i]
Assuming mr FMc are correct, there is in python 3.5 a valid approach to merge dicts. Which in this case would led us to:
dicts = [
{'id': '1', 'b': '2', 'c': '3'},
{'id': '4', 'b': '5', 'c': '6'},
{'id': '7', 'b': '8', 'c': ''},
]
d_dicts = [
{'d': '30', 'id': '1'},
{'d': '25', 'id': '4'},
]
dicts = [{**d, **dict(*filter(lambda x: x["id"] == d["id"], d_dicts))} for d in dicts]
I like these kinda expressions instead of writing it all out, but it has the "benefit" of crashing instead of overwriting stuff when there is more then one dict with the same id. But my solution still overwrites values if there are duplicate keys silently. The inserted value being the value from whatever's second in the dict merge.
This question already has answers here:
How do I sort a list of dictionaries by a value of the dictionary?
(20 answers)
Closed 7 years ago.
I have a list of this type :
l = [{"id":"21", "region" :['2', '6', '4']}, {"id":"12", "region" :['1', '3', '8']}]
I want to sort the list on the "region" field, and that also at 2nd index.
that is :
l = [{"id":"21", "region" :['2', **'6'**, '4']}, {"id":"12", "region" :['1', **'3'**, '8']}]
How do I do it ? I am aware of itemgetter. But couldn't do with that also.
You can use list.sort() with key argument, passing a lambda expression to the key argument -
In [45]: l = [{"id":"21", "region" :['2', '6', '4']}, {"id":"12", "region" :['1', '3', '8']}]
In [46]: l.sort(key=lambda x: x['region'][1])
In [47]: l
Out[47]:
[{'id': '12', 'region': ['1', '3', '8']},
{'id': '21', 'region': ['2', '6', '4']}]
refer to sorted(iterable, cmp=None, key=None, reverse=False)
>>> l = [{"id":"21", "region" :['2', '6', '4']}, {"id":"12", "region" :['1', '3', '8']}]
>>> print sorted(l, key=lambda x: x['region'][1], reverse=False)
[{'region': ['1', '3', '8'], 'id': '12'}, {'region': ['2', '6', '4'], 'id': '21'}]
>>> print l
[{'region': ['2', '6', '4'], 'id': '21'}, {'region': ['1', '3', '8'], 'id': '12'}]