How can I convert a Python-like dictionary into a flutter list?
here's my python dict fetched from a dataframe:
{0: {'id': '3422',
'Name': 'John',
}
1: {'id': '3322',
'Name': 'Mark',
}}
I want to convert it in this way:
final allUsers = <User>[
User(id: '3422', name:'John'),
User(id: '3322', name: 'Mark')]
dic = {0: {'id': '3422',
'Name': 'John',},
1: {'id': '3322',
'Name': 'Mark',
}}
flutter_value = ""
f_count = 0
for i in dic:
f_count+=1
count = 0
for j in dic[i]:
count+=1
if count == 1:
flutter_value+='User('+j+":'"+dic[i][j]+"'"
else:
flutter_value+=","+j+":'"+dic[i][j]+"')"
if f_count!=len(dic):
flutter_value+=","
flutter_value = ("final allUsers = <User>["+flutter_value+"]")
print(flutter_value)
Not sure how generic it is, but it can help you in small run I guess.
Output:
final allUsers = <User>[User(id: '3422', Name: 'John'),User(id: '3322', Name: 'Mark')]
Related
I have one list of elements and another list of dictionaries and i want to insert list of elements into each dictionary of list
list_elem = [1,2,3]
dict_ele = [{"Name":"Madhu","Age":25},{"Name":"Raju","Age:24},{""Name":"Mani","Age":12}],
OUTPUT As:
[{"ID":1,"Name":"Madhu","Age":25},{"ID":2,"Name":"Raju","Age:24},{"ID":3,"Name":"Mani","Age":12}]
I have tried this way :
dit = [{"id":item[0]} for item in zip(sam)]
# [{"id":1,"id":2,"id":3}]
dic1 = list(zip(dit,data))
print(dic1)
# [({"id":1},{{"Name":"Madhu","Age":25}},{"id":2},{"Name":"Raju","Age:24},{"id":3},{""Name":"Mani","Age":12})]
What is the most efficient way to do this in Python?
Making an assumption here that the OP's original question has a typo in the definition of dict_ele and also that list_elem isn't really necessary.
dict_ele = [{"Name":"Madhu","Age":25},{"Name":"Raju","Age":24},{"Name":"Mani","Age":12}]
dit = [{'ID': id_, **d} for id_, d in enumerate(dict_ele, 1)]
print(dit)
Output:
[{'ID': 1, 'Name': 'Madhu', 'Age': 25}, {'ID': 2, 'Name': 'Raju', 'Age': 24}, {'ID': 3, 'Name': 'Mani', 'Age': 12}]
dict_ele = [{"Name":"Madhu","Age":25},{"Name":"Raju","Age":24},{"Name":"Mani","Age":12}]
list_elem = [1,2,3]
[{'ID': id, **_dict} for id, _dict in zip(list_elem, dict_ele)]
[{'ID': 1, 'Name': 'Madhu', 'Age': 25}, {'ID': 2, 'Name': 'Raju', 'Age': 24}, {'ID': 3, 'Name': 'Mani', 'Age': 12}]
try this: r = [{'id':e[0], **e[1]} for e in zip(list_elem, dict_ele)]
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))
I'm trying to learn python. Assuming I have the below two dict().
In the 1st dict, it includes user info and the reporting line structures.
In the 2nd dict, it includes item counts belong to each individual.
I want to compare again these two dict and sum up the total item counts then display the result under name_S. The outcome is shown as follow:
data_set_1 = { 'id': 'mid',
'name': 'name_S',
'directory': [
{
'id': 'eid_A',
'name': 'name_A',
'directory': []
},
{ 'id': 'eid_B',
'name': 'name_B',
'directory': []
},
{ 'id': 'eid_C',
'name': 'name_C',
'directory': [
{'id': 'eid_C1',
'name': 'name_C1',
'directory': []},
{'id': 'eid_C2',
'name': 'name_C2',
'directory': []}]
}]}
data_set_2 = { 'eid_A': 5,
'eid_F': 3,
'eid_G': 0,
'eid_C': 1,
'eid_C1': 10,
'eid_C2': 20
}
Result:
{'name_S': 36}
I'm able to get the result if I did this way:
def combine_compare(data_set_1, data_set_2):
combine_result = dict()
combine_id = data_set_1['id']
combine_name = data_set_1['name']
combine_directory = data_set_1['directory']
if combine_directory:
combine_item_sum = 0
combine_item_count = data_set_2.get(combine_id, 0)
for combine_user in combine_directory:
# Recursion starts
for i in [combine_compare(combine_user, data_set_2)]:
for key, value in i.items():
combine_item_sum += value
combine_result[combine_name] = combine_item_sum + combine_item_count
else:
combine_result[combine_name] = data_set_2.get(combine_id, 0)
return combine_result
Now if I want to include the ids that have item counts in the final result, something like this:
#if there is result and directory is not None under name_S
{'name_S': [36, ('eid_A', 'eid_C', eid_C1', 'eid_C2')]}
#if there is no result and directory is not None under name_S, display a default str
{'name_S': [0, ('Null')]}
#if there is result and directory is None under name_S, display name_S id
{'name_S': [1, ('mid')]}
My original idea is to create a list and append the counts and ids but I'm struggling how I can accomplish this. Here is what I try but the list is not returning the outcome I'm expecting and I'm not sure how I can append the count in the list. Any help would be greatly appreciated.
def combine_compare(data_set_1, data_set_2):
combine_result = dict()
# Creating a new list
combine_list = list()
combine_id = data_set_1['id']
combine_name = data_set_1['name']
combine_directory = data_set_1['directory']
if combine_directory:
combine_item_sum = 0
combine_item_count = data_set_2.get(combine_id, 0)
for combine_user in combine_directory:
# Recursion starts
for i in [combine_compare(combine_user, data_set_2)]:
for key, value in i.items():
combine_item_sum += value
# Trying to append the ids where count > 0
if data_set_2.get(combine_user['id'], 0) != 0:
combine_list.append(combine_user['id'])
combine_result[combine_name] = combine_item_sum + combine_item_count
else:
combine_result[combine_name] = data_set_2.get(combine_id, 0)
# Trying to print the list to see the results
print(combine_list)
return combine_result
So what i understood from your question is that you want to know which ids mentioned in data_set_2 are there in data_set_1 and what is there sum. The following code is my version of solving the above mentioned problem.
data_set_1 = { 'id': 'mid',
'name': 'name_S',
'directory': [
{
'id': 'eid_A',
'name': 'name_A',
'directory': []
},
{ 'id': 'eid_B',
'name': 'name_B',
'directory': []
},
{ 'id': 'eid_C',
'name': 'name_C',
'directory': [
{'id': 'eid_C1',
'name': 'name_C1',
'directory': []},
{'id': 'eid_C2',
'name': 'name_C2',
'directory': []
}
]
}
]
}
data_set_2 = { 'eid_A': 5,
'eid_F': 3,
'eid_G': 0,
'eid_C': 1,
'eid_C1': 10,
'eid_C2': 20
}
value = 0
final_result={}
def compare(d1,d2):
global value
temp_result={}
if d1['name'] not in temp_result:
temp_result[d1['name']]=[]
for items in d1['directory']:
if items['directory']:
temp_value=compare(items,d2)
temp_result[d1['name']].append(temp_value)
result=check_for_value(items,d2)
if result:
value+=result
temp_result[d1['name']].append(items['id'])
return temp_result
def check_for_value(d,d2):
if d['id'] in d2:
return d2[d['id']]
final_result=compare(data_set_1,data_set_2)
final_result['value']=value
print("final_result:",final_result)
Which gives you an output dict which tells you exactly under which name does those ids come under.
The output is as follows:
final_result: {'value': 36, 'name_S': ['eid_A', {'name_C': ['eid_C1', 'eid_C2']}, 'eid_C']}
You can change the structure of the final result to make it exactly how you want it to be. Let me know if you have any trouble understanding the program.
I've have the problem where I have a dict of the passengers like this:
passengers = {
1: {'name': 'Foo', 'lastname': 'Bar', 'exclusive': True},
2: {'name': 'John', 'lastname': 'Doe'},
3: {'name': 'Rocky', 'lastname': 'Balboa', 'exclusive': True},
4: {'name': 'Mohammed', 'lastname': 'Smith'}
}
And I need to print the results like this items with exclusive first then the rest:
THIS IS THE DESIRED OUTPUT
List of passengers:
===================
1.- Foo Bar
2.- Rocky Balboa
3.- John Doe
4.- Mohammed Smith
I tried with collections.deque, and I haven't found anything that works for me, until I came up with this function:
def prioritize_passengers(dictionary):
priority_list = []
normal_list = []
sorted_list = []
for key, item in dictionary.iteritems():
if 'exclusive' in item:
priority_list.append(key)
else:
normal_list.append(key)
sorted_list = priority_list + normal_list
return sorted_list
And then I use it on my data like this:
# Assuming passenger is the same var as above
sorted_list = prioritize_passengers(passengers)
print "List of passengers:\n==================="
for elem in sorted_list:
passenger = passengers[elem]
print "{} {}".format(passenger['name'], passenger['lastname']
Is that the only way to do it or is there a more clear/efficient way to achieve it? Again, the second paragraph is the desired output.
Yes, there are other ways to sort that list. Here is one:
passengers = {
1: {'name': 'Foo', 'lastname': 'Bar', 'exclusive': True},
2: {'name': 'John', 'lastname': 'Doe'},
3: {'name': 'Rocky', 'lastname': 'Balboa', 'exclusive': True},
4: {'name': 'Mohammed', 'lastname': 'Smith'}
}
list_of_passengers = sorted(
passengers.items(),
key=lambda x: (('exclusive' not in x[1]), x[0]))
for i, (_, passenger) in enumerate(list_of_passengers, 1):
print '{}. - {} {}'.format(i, passenger['name'], passenger['lastname'])
Since you don't care about the order other than the exclusive-ness, then you this might work for you:
passengers = {
1: {'name': 'Foo', 'lastname': 'Bar', 'exclusive': True},
2: {'name': 'John', 'lastname': 'Doe'},
3: {'name': 'Rocky', 'lastname': 'Balboa', 'exclusive': True},
4: {'name': 'Mohammed', 'lastname': 'Smith'}
}
list_of_passengers = sorted(
passengers.values(), key=lambda x: 'exclusive' not in x)
for i, passenger in enumerate(list_of_passengers, 1):
print '{}. - {} {}'.format(i, passenger['name'], passenger['lastname'])
Finally, if what you really want to do is to create two separate lists, you can use the filter() builtin funciton:
upper_crust = filter(lambda x: 'exclusive' in x, passengers.values())
riff_raff = filter(lambda x: 'exclusive' not in x, passengers.values())
I have an error with this line. I am working with a dictionary from a file with an import. This is the dictionary:
users = [{'id':1010,'name':"Administrator",'type':1},{'id':1011,'name':"Administrator2",'type':1}]
And the method with which the work is as follows:
def addData(dict, entry):
new = {}
x = 0
for i in dict.keys():
new[i] = entry(x)
x += 1
dict.append(new)
Where "dict" would be "users", but the error is that the dictionary does not recognize me as such. Can anyone tell me, I have wrong in the dictionary?
That's not a dicionary, it's a list of dictionaries!
EDIT: And to make this a little more answer-ish:
users = [{'id':1010,'name':"Administrator",'type':1},{'id':1011,'name':"Administrator2",'type':1}]
newusers = dict()
for ud in users:
newusers[ud.pop('id')] = ud
print newusers
#{1010: {'type': 1, 'name': 'Administrator'}, 1011: {'type': 1, 'name': 'Administrator2'}}
newusers[1012] = {'name': 'John', 'type': 2}
print newusers
#{1010: {'type': 1, 'name': 'Administrator'}, 1011: {'type': 1, 'name': 'Administrator2'}, 1012: {'type': 2, 'name': 'John'}}
Which is essentially the same as dawgs answer, but with a simplified approach on generating the new dictionary
Perhaps you are looking to do something along these lines:
users = [{'id':1010,'name':"Administrator",'type':1},{'id':1011,'name':"Administrator2",'type':1}]
new_dict={}
for di in users:
new_dict[di['id']]={}
for k in di.keys():
if k =='id': continue
new_dict[di['id']][k]=di[k]
print new_dict
# {1010: {'type': 1, 'name': 'Administrator'}, 1011: {'type': 1, 'name': 'Administrator2'}}
Then you can do:
>>> new_dict[1010]
{'type': 1, 'name': 'Administrator'}
Essentially, this is turning a list of anonymous dicts into a dict of dicts that are keys from the key 'id'