How to get lenght of dict keys after specific element? - python

There is a dict
example_dict =
{'spend': '3.91',
'impressions': '791',
'clicks': '19',
'campaign_id': '1111',
'date_start': '2017-11-01',
'date_stop': '2019-11-27',
'age': '18-24',
'gender': 'male'}
I have to check if there are any additional keys after date_stop key and if yes, get the lenght of them and their names.
So far I made a list of keys
list_keys = list(example_dict.keys())
list_keys =
['spend',
'impressions',
'clicks',
'campaign_id',
'date_start',
'date_stop',
'age',
'gender']
And to check that there is 'date_stop' element is simple
if 'date_stop' in list_keys:
# what next
But how to proceed am not sure. Appreciate any help.

I guess it should be implement in diffrent way, You should be using dict, but if You really want to do this way You could use OrderedDict from collections:
from collections import OrderedDict
my_dict = {
'spend': '3.91',
'impressions': '791',
'clicks': '19',
'campaign_id': '1111',
'date_start': '2017-11-01',
'date_stop': '2019-11-27',
'age': '18-24',
'gender': 'male'
}
sorted_ordered_dict = OrderedDict(sorted(my_dict.items(), key=lambda t: t[0]))
if 'date_stop' in sorted_ordered_dict.keys():
keys = list(sorted_ordered_dict.keys())
index = keys.index('date_stop')
after_list = keys[index:]
print('len: ', len(after_list))
print('list: ', after_list)

use below code:
new_dict={}
list_keys = list(example_dict.keys())
k=""
for i in list_keys:
if 'date_stop' == i:
k="done"
if k=="done":
new_dict[i]=len(i)
output:
{'date_stop': 9, 'age': 3, 'gender': 6}
I hope you understand your question
if you want just name and number of keys use this:
new_dict=[]
list_keys = list(example_dict.keys())
k=""
for i in list_keys:
if 'date_stop' == i:
k="done"
if k=="done":
new_dict.append(i)
output:
print (new_dict)
print (len(new_dict))
['date_stop', 'age', 'gender']
3

Related

Convert list of dictionaries with different keys to values string list

Example list of dicts:
[{'name': 'aly', 'age': '104'}, {'name': 'Not A name', 'age': '99'}]
Expected out = ['aly', '104', 'Not A name', '99']
Any help will be much appreciated.
Thanks!
Try this in one line:
d = [{'name': 'aly', 'age': '104'}, {'name': 'Not A name', 'age': '99'}]
[v for i in d for k,v in i.items()]
The result will be:
Out[1]: ['aly', '104', 'Not A name', '99']
Another way :
listDictionary = [{'name': 'aly', 'age': '104'}, {'name': 'Not A name', 'age': '99'}]
out = []
for i in listDictionary:
for k, v in i.items():
out.append(v)
print(out)
Output : ['aly', '104', 'Not A name', '99']

convert list of values in dictionary to key pair value

Hi iam having below dictionary with values as list
a={'Name': ['ANAND', 'kumar'], 'Place': ['Chennai', 'Banglore'], 'Designation': ['Developer', 'Sr.Developer']}
iam just expecting output like this:
a=[{"Name":"ANAND",'Place':'Chennai','Designation':'Developer'},{"Name":"kumar",'Place':'Banglore','Designation':'Sr.Developer'}]
You can try in this way:
a={'Name': ['ANAND', 'kumar'], 'Place': ['Chennai', 'Banglore'], 'Designation': ['Developer', 'Sr.Developer']}
out = []
keys = list(a.keys())
for i in range(len(a[keys[0]])):
temp = {}
for j in keys:
temp[j] = a[j][i]
out.append(temp)
print(out)
#Output - [{'Name': 'ANAND', 'Place': 'Chennai', 'Designation': 'Developer'}, {'Name': 'kumar', 'Place': 'Banglore', 'Designation': 'Sr.Developer'}]
Use list comprehension
newlist = []
newlist.append({key: value[0] for key, value in a.items()})
newlist.append({key: value[1] for key, value in a.items()})
If the length is long:
newlist = []
for i in range(len(a[list(a.keys())[0]])):
newlist.append({key: value[i] for key, value in a.items()})
this should do the trick :
a={'Name': ['ANAND', 'kumar'], 'Place': ['Chennai', 'Banglore'], 'Designation': ['Developer', 'Sr.Developer']}
ans = []
num_of_dicts = len(list(a.values())[0])
for i in range(num_of_dicts):
ans.append({key:val[i] for key,val in a.items() })
print(ans)
output:
[{'Name': 'ANAND', 'Place': 'Chennai', 'Designation': 'Developer'}, {'Name': 'kumar', 'Place': 'Banglore', 'Designation': 'Sr.Developer'}]
if you have any questions feel free to ask me in the commennts :)
Try this. It just converts to dictionary into a DataFrame and to_dict rearranges it back into a dictionary (according to records).
import pandas as pd
a={'Name': ['ANAND', 'kumar'], 'Place': ['Chennai', 'Banglore'], 'Designation': ['Developer', 'Sr.Developer']}
pd.DataFrame(a).to_dict('records')
Output
[{'Designation': 'Developer', 'Name': 'ANAND', 'Place': 'Chennai'},
{'Designation': 'Sr.Developer', 'Name': 'kumar', 'Place': 'Banglore'}]

From list to nested dictionary

there are list :
data = ['man', 'man1', 'man2']
key = ['name', 'id', 'sal']
man_res = ['Alexandra', 'RST01', '$34,000']
man1_res = ['Santio', 'RST009', '$45,000']
man2_res = ['Rumbalski', 'RST50', '$78,000']
the expected output will be nested output:
Expected o/p:- {'man':{'name':'Alexandra', 'id':'RST01', 'sal':$34,000},
'man1':{'name':'Santio', 'id':'RST009', 'sal':$45,000},
'man2':{'name':'Rumbalski', 'id':'RST50', 'sal':$78,000}}
Easy way would be using pandas dataframe
import pandas as pd
df = pd.DataFrame([man_res, man1_res, man2_res], index=data, columns=key)
print(df)
df.to_dict(orient='index')
name id sal
man Alexandra RST01 $34,000
man1 Santio RST009 $45,000
man2 Rumbalski RST50 $78,000
{'man': {'name': 'Alexandra', 'id': 'RST01', 'sal': '$34,000'},
'man1': {'name': 'Santio', 'id': 'RST009', 'sal': '$45,000'},
'man2': {'name': 'Rumbalski', 'id': 'RST50', 'sal': '$78,000'}}
Or you could manually merge them using dict + zip
d = dict(zip(
data,
(dict(zip(key, res)) for res in (man_res, man1_res, man2_res))
))
d
{'man': {'name': 'Alexandra', 'id': 'RST01', 'sal': '$34,000'},
'man1': {'name': 'Santio', 'id': 'RST009', 'sal': '$45,000'},
'man2': {'name': 'Rumbalski', 'id': 'RST50', 'sal': '$78,000'}}
#save it in 2D array
all_man_res = []
all_man_res.append(man_res)
all_man_res.append(man1_res)
all_man_res.append(man2_res)
print(all_man_res)
#Add it into a dict output
output = {}
for i in range(len(l)):
person = l[i]
details = {}
for j in range(len(key)):
value = key[j]
details[value] = all_man_res[i][j]
output[person] = details
output
The pandas dataframe answer provided by NoThInG makes the most intuitive sense. If you are looking to use only the built in python tools, you can do
info_list = [dict(zip(key,man) for man in (man_res, man1_res, man2_res)]
output = dict(zip(data,info_list))

Compare dicts but get result with source

Hello I need to compare 2 dicts but in the result, I need to know from which dict the result came.
dict1 = {'name': 'Morgan', 'surename': 'Finch'}
dict2 = {'name': 'David', 'surename': 'Finch'}
so if I compare with input_data.items() ^ response_data.items() result will something like this:
{('name','Morgan'),('name', 'David)}
expected result should look something like {'dict1': ('name','Morgan'), dict2: ('name', 'David')}
I don't care what data-structure just that I could know from what dict it came.
dict1 = {'name': 'Morgan', 'surname': 'Finch'}
dict2 = {'name': 'David', 'surname': 'Finch'}
# symmetric difference (exclusive OR)
print(dict1.items() ^ dict2.items())
# {('name', 'Morgan'), ('name', 'David')}
# dictionary subtraction
print({'dict1': dict1.items() - dict2.items(), 'dict2': dict2.items() - dict1.items()})
# {'dict1': {('name', 'Morgan')} 'dict2': {('name', 'David')}}
If you want the answer in the form of dictionary
You can use these steps
dict1 = {'name': 'Morgan', 'surename': 'Finch'}
dict2 = {'name': 'David', 'surename': 'Finch'}
dict3 = {}
for k,v in dict1.items():
if dict1[k] != dict2[k]:
dict3['dict1'] = (k,dict1[k])
dict3['dict2'] = (k,dict2[k])
print(dict3)
Output:
{'dict1': ('name', 'Morgan'), 'dict2': ('name', 'David')}
Edit:
If all values are different and want to store in a single key like {'dict1' : ('name', 'Morgan', 'surname', 'Finc'), ... }
dict1 = {'name': 'Morgan', 'surename': 'Finch'}
dict2 = {'name': 'David', 'surename': 'Finc'}
dict3 = {'dict1':(), 'dict2':()}
for k,v in dict1.items():
if dict1[k] != dict2[k]:
dict3['dict1'] += (k,dict1[k])
dict3['dict2'] += (k,dict2[k])
print(dict3)
Output:
{'dict1': ('name', 'Morgan', 'surename', 'Finch'), 'dict2': ('name', 'David', 'surename', 'Finc')}

Creating a dictionary from two lists in python

I have a JSON data as below.
input_list = [["Richard",[],{"children":"yes","divorced":"no","occupation":"analyst"}],
["Mary",["testing"],{"children":"no","divorced":"yes","occupation":"QA analyst","location":"Seattle"}]]
I have another list where I have the prospective keys present
list_keys = ['name', 'current_project', 'details']
I am trying to create a dic using both to make the data usable for metrics
I have summarized the both the list for the question but it goes on forever, there are multiple elements in the list. input_list is a nested list which has 500k+ elements and each list element have 70+ elements of their own (expect the details one)
list_keys also have 70+ elements in it.
I was trying to create a dict using zip but that its not helping given the size of data, also with zip I am not able to exclude the "details" element from
I am expecting output something like this.
[
{
"name": "Richard",
"current_project": "",
"children": "yes",
"divorced": "no",
"occupation": "analyst"
},
{
"name": "Mary",
"current_project" :"testing",
"children": "no",
"divorced": "yes",
"occupation": "QA analyst",
"location": "Seattle"
}
]
I have tried this so far
>>> for line in input_list:
... zipbObj = zip(list_keys, line)
... dictOfWords = dict(zipbObj)
...
>>> print dictOfWords
{'current_project': ['testing'], 'name': 'Mary', 'details': {'location': 'Seattle', 'children': 'no', 'divorced': 'yes', 'occupation': 'QA analyst'}}
but with this I am unable to to get rid of nested dict key "details". so looking for help with that
Seems like what you wanted was a list of dictionaries, here is something i coded up in the terminal and copied in here. Hope it helps.
>>> list_of_dicts = []
>>> for item in input_list:
... dict = {}
... for i in range(0, len(item)-2, 3):
... dict[list_keys[0]] = item[i]
... dict[list_keys[1]] = item[i+1]
... dict.update(item[i+2])
... list_of_dicts.append(dict)
...
>>> list_of_dicts
[{'name': 'Richard', 'current_project': [], 'children': 'yes', 'divorced': 'no', 'occupation': 'analyst'
}, {'name': 'Mary', 'current_project': ['testing'], 'children': 'no', 'divorced': 'yes', 'occupation': '
QA analyst', 'location': 'Seattle'}]
I will mention it is not the ideal method of doing this since it relies on perfectly ordered items in the input_list.
people = input_list = [["Richard",[],{"children":"yes","divorced":"no","occupation":"analyst"}],
["Mary",["testing"],{"children":"no","divorced":"yes","occupation":"QA analyst","location":"Seattle"}]]
list_keys = ['name', 'current_project', 'details']
listout = []
for person in people:
dict_p = {}
for key in list_keys:
if not key == 'details':
dict_p[key] = person[list_keys.index(key)]
else:
subdict = person[list_keys.index(key)]
for subkey in subdict.keys():
dict_p[subkey] = subdict[subkey]
listout.append(dict_p)
listout
The issue with using zip is that you have that additional dictionary in the people list. This will get the following output, and should work through a larger list of individuals:
[{'name': 'Richard',
'current_project': [],
'children': 'yes',
'divorced': 'no',
'occupation': 'analyst'},
{'name': 'Mary',
'current_project': ['testing'],
'children': 'no',
'divorced': 'yes',
'occupation': 'QA analyst',
'location': 'Seattle'}]
This script will go through every item of input_list and creates new list where there aren't any list or dictionaries:
input_list = [
["Richard",[],{"children":"yes","divorced":"no","occupation":"analyst"}],
["Mary",["testing"],{"children":"no","divorced":"yes","occupation":"QA analyst","location":"Seattle"}]
]
list_keys = ['name', 'current_project', 'details']
out = []
for item in input_list:
d = {}
out.append(d)
for value, keyname in zip(item, list_keys):
if isinstance(value, dict):
d.update(**value)
elif isinstance(value, list):
if value:
d[keyname] = value[0]
else:
d[keyname] = ''
else:
d[keyname] = value
from pprint import pprint
pprint(out)
Prints:
[{'children': 'yes',
'current_project': '',
'divorced': 'no',
'name': 'Richard',
'occupation': 'analyst'},
{'children': 'no',
'current_project': 'testing',
'divorced': 'yes',
'location': 'Seattle',
'name': 'Mary',
'occupation': 'QA analyst'}]

Categories