I have a python code like this:
experiment_str = ['0', '1', '2', '3', '4', '5']
conversation_dict = dict.fromkeys(experiment_str,[])
conversation_dict['0'].append(10)
I want to add 10 to only the first key but it adds to all keys. Can you please help me to understand it?
For a dictionary you shouldn't be using the .append method, simply use '=':
conversation_dict['0'] = 10
as well as this, if you want to create a new key, use the same method.
Related
I have a nested dictionary where i am trying to print the corresponding value of the nested key without requiring the outermost numeral key input.
e.g. if roomname in nested-nested dictionary, print room area.
and my dictionary is set up like below:
d = {0: {'RoomName': 'PSC', 'MinArea': '28', 'MinRoomDim': 'null', 'MinDoorWidth': '900', 'MinDoorHeight': '2100', 'NoofDoorLeaves': '1', 'DoorMaterial': 'Glass', 'ReferenceLocation': 'LTA ADC SECTION 3.1 CLAUSE 5.1', 'RoomSpecificInfo': 'Refer to PSC design guidelines'},
1: {'RoomName': 'SMR', 'MinArea': '8', 'MinRoomDim': 'null', 'MinDoorWidth': '900', 'MinDoorHeight': '2100', 'NoofDoorLeaves': '1', 'DoorMaterial': 'Glass', 'ReferenceLocation': 'LTA ADC SECTION 3.1 CLAUSE 5.2', 'RoomSpecificInfo': 'null'},
2: {'RoomName': 'FIRST AID RM', 'MinArea': '7.5', 'MinRoomDim': '3.0m x 2.5m', 'MinDoorWidth': '1000', 'MinDoorHeight': '2100', 'NoofDoorLeaves': '1', 'DoorMaterial': 'null', 'ReferenceLocation': 'LTA ADC SECTION 3.1 CLAUSE 5.3', 'RoomSpecificInfo': 'null'},...
So far all the solutions I managed to find are for typical dictionaries and the solution does not work for nested dictionaries like above. Any help would be appreciated.
You can print nested dictionaries like this:
for i,j in d.items():
for m,n in j.items():
print(m,n)
where m is the key and n is the value of the nested dictionary
Read the json file and then use multiple loads and get() inside to get the required value in the nested json for example to get in key '1' to get RoomName
json.loads(json.loads(x).get("1","{}")).get("RoomName"))
I have a list from dataframe like this:
prod_id = data["id"].tolist()
prod_id
['2',
'4',
'6',
'8',
'10',
'12',
'14',
'16',
'18',
'20',
'22',
And, I am calling a API with parameter id = 14
bx24.callMethod('crm.deal.productrows.get',
id = 14)
How can I call the API for all id from my list (prod_id)?
You can use Series.apply and skip the list creation. I also believe you will gain some speed if there are a lot of values.
The only downside is you will need to flip the order of the arguments, so if you don't control bx24.callMethod's code you will need to wrap it.
def api_call(id, path):
bx24.callMethod(path, id)
data['id'].apply(api_call, args=('crm.deal.productrows.get',))
# or with lambda
data['id'].apply(lambda id, path: bx24.callMethod(path, id), args=('crm.deal.productrows.get',))
If you do control bx24.callMethod's code then all is required is (after changing its signature to id, path)
data['id'].apply(bx24.callMethod, args=('crm.deal.productrows.get',))
I am trying to limit the ordering of a dictionary but the ouput that I get are returned in a sorted order which is something I do not want.
test = {}
test['bbb'] = '0'
test['aaa'] = '1'
# Returns me {'aaa': '1', 'bbb': '0'} when I am expecting {'bbb': '0', 'aaa': '1'}
The above is a simple example, in which both aaa and bbb are queried from a list. And I had thought this may have resolves the ordering but it did not.
Dictionary is not preserving the order of added elements. You need to use collections.OrderedDict instead to have this feature available.
This question already has answers here:
How to print a list in Python "nicely"
(11 answers)
Closed 5 years ago.
I've used a draft code and adapted it to suit my code but I don't know how to split the data. The question might seem a vague so I'll try to be help by saying what I want.
My code:
import csv
with open("scores.csv") as csv_data:
reader=csv.reader(csv_data,delimiter=",")
number_sorted=sorted(reader,key=lambda x:int(x[0]),reverse=True)
print(number_sorted)
I get the output:
[['25356767', 'tom'], ['443388', 'jin'], ['6744', 'trev'], ['4666', 'ryan'],
['2445', 'jones'], ['536', 'sue'], ['34', 'bob'], ['8', 'hera'], ['1',
'bill'], ['0', 'v']]
but I want the print to look like this so it looks like a leader board:
`[['25356767', 'tom'],
['443388', 'jin'],
['6744', 'trev'],
['4666', 'ryan'],
['2445', 'jones'],
['536', 'sue'],
['34', 'bob'],
['8', 'hera'],
['1', 'bill'],
['0', 'v']]`
I hope that explains my question.
Can't do that, sorry.
What you're asking to do is, essentially, altering the way the console outputs lists. Simpler (and, probably, prettier) would be to define a function to pretty print the lists.
If you did something like:
def pretty(inlist):
for score, name in inlist:
print name.rjust(10) +"| " +score
Then it would print every line in a pretty format.
I have 2 nested dictionaries in Python that have this format:
1166869: {'probL2': '0.000', 'probL1': '0.000', 'pronNDiff_site': '1.000', 'StateBin': '0', 'chr': 'chrX', 'rangehist': '59254000-59255000', 'start_bin': '59254000', 'countL2': '4', 'countL1': '0'}
1166870: {'probL2': '0.148', 'probL1': '0.000', 'pronNDiff_site': '0.851', 'StateBin': '0', 'chr': 'chr2', 'rangehist': '59254000-59255000', 'start_bin': '59255000', 'countL2': '5', 'countL1': '15'}
1166871: {'probL2': '0.000', 'probL1': '0.000', 'pronNDiff_site': '1.000', 'StateBin': '0', 'chr': 'chrY', 'rangehist': '59290000-59291000', 'start_bin': '59290000', 'countL2': '1', 'countL1': '2'}
where 1166869, 1166870 and 1166871 represent a line in a file from where I read the data, and the rest of the keys are the data itself.
Now I want to make a list where I store all the different values in the key "chr" because there are some repeated ones.
How can I go through the dictionary and make the comparison between the 2 values? This code is not working:
for k in range(len(file_dict)):
for j in range(len(file_dict)-1):
if (file_dict[j]["chr"] != file_dict[k]["chr"]):
list_chr.append(file_dict[j]["chr"])
Use a set, and just all the items in one go:
chr = { v['chr'] for v in file_dict.itervalues() }
This uses a set comprehension to generate your set in one line of code.
Set comprehensions were introduced in Python 2.7; in earlier versions use:
chr = set(v['chr'] for v in file_dict.itervalues())
In Python 3, you'd need to replace .itervalues() by .values().
Your own code doesn't work because python dictionaries are not lists; you don't retrieve values by index, but by key. You'd have to change it to:
for key in file_dict:
for other_key in file_dict:
if key == other_key:
continue
if file_dict[key]['chr'] != file_dict[otherkey]['chr']:
list_chr.append(filed_dict[key]['chr'])
but that is really inefficient, not to mention incorrect.
how about something along the lines of:
list_chr = list(set([val['chr'] for val in file_dict.values()]))
how does this work?
first a list comprehension gets all the chr entries in the inner dict
these are then converted to a set, such that there are no duplicate entries
these are then converted to a list if that's the format you prefere
please note that maybe you really want to use a set, then the look up time is O(1) instead of O(n)