There is a list of values:
list_inside = ["de:14612:1","de:14612:21","de:14612:17","de:14612:16"]
Why instead of {'from': '1', 'to': '16'} I am getting this {'from': '16', 'to': '16'}. What I am doing wrong with my code?
keys = ["from", "to"]
list_inside = ["de:14612:1","de:14612:21","de:14612:17","de:14612:16"]
for i in list_inside[::len(list_inside)-1]:
result = dict((key, i.join(i.split(":", 2)[2::1])) for key in keys)
print(result)
Use
keys = ["from", "to"]
list_inside = ["de:14612:1","de:14612:21","de:14612:17","de:14612:16"]
result = {} #Declare empty dict
for key, v in zip(keys, list_inside[::len(list_inside)-1]):
result.update({key: v.split(":", 2)[-1])}) #Use dict.update to update the required values.
print(result)
Output:
{'to': '16', 'from': '1'}
Your current approach is overriding result variable.
Your doing result = several times inside a loop.
Obviously, only the last iteration will be effective here.
This code gets the result what you are expecting.
-1 made simple code.
keys = ["from", "to"]
list_inside = ["de:14612:1","de:14612:21","de:14612:17","de:14612:16"]
result = {}
result[keys[0]] = list_inside[0].split(':')[2]
result[keys[1]] = list_inside[-1].split(':')[2]
print (result)
Related
Say I have two Dictionaries (or could be Arrays), each having sub-dictionaries (or sub-arrays):
var dict_A = {'a': 1, 'sub_dict': {'hello': 'world', 'quick': 'fox'}}
var dict_B = {'b': 2, 'sub_dict': {'hello': 'godot'}}
Is there a builtin method in GDScript to merge them, including the sub-dictionaries or sub-arrays?
Expected result would be:
merge_dict(dict_A, dict_B)
# {'a': 1, 'b': 2, 'sub_dict': {'hello': 'godot', 'quick': 'fox'}}
There's no builtin method in GDScript for that, but you can use the following functions (find usage examples, unit tests, and more on this Github gist):
Observation: when using deep_merge=true with merge_array, all sub-dictionaries and sub-arrays must be JSON serializable.
func merge_array(array_1: Array, array_2: Array, deep_merge: bool = false) -> Array:
var new_array = array_1.duplicate(true)
var compare_array = new_array
var item_exists
if deep_merge:
compare_array = []
for item in new_array:
if item is Dictionary or item is Array:
compare_array.append(JSON.print(item))
else:
compare_array.append(item)
for item in array_2:
item_exists = item
if item is Dictionary or item is Array:
item = item.duplicate(true)
if deep_merge:
item_exists = JSON.print(item)
if not item_exists in compare_array:
new_array.append(item)
return new_array
func merge_dict(dict_1: Dictionary, dict_2: Dictionary, deep_merge: bool = false) -> Dictionary:
var new_dict = dict_1.duplicate(true)
for key in dict_2:
if key in new_dict:
if deep_merge and dict_1[key] is Dictionary and dict_2[key] is Dictionary:
new_dict[key] = merge_dict(dict_1[key], dict_2[key])
elif deep_merge and dict_1[key] is Array and dict_2[key] is Array:
new_dict[key] = merge_array(dict_1[key], dict_2[key])
else:
new_dict[key] = dict_2[key]
else:
new_dict[key] = dict_2[key]
return new_dict
This code is licensed under BSD 3-Clause License | Copyright 2022 Hackverse.org
I want to sort a dictionary by descending order by a value of a key within a key.
In my sample, I want to sort by little 'c'
Here is what I looks like now:
sample = {'A': {'a':22, 'b':24, 'c':80},
'B': {'a':12, 'b':13, 'c':55},
'C': {'a':44, 'b':33, 'c':99}
}
and here is my desired output:
sample = {'C': {'a':44, 'b':33, 'c':99},
'A': {'a':22, 'b':24, 'c':80},
'B': {'a':12, 'b':13, 'c':55}
}
I tried this bit of code by clearly its not right:
newdict = {}
for key, value in sorted(sample.items(), key=lambda item: item['c'], reverse=True):
newdict[key] = value
sample = newdict
Thank you all for the help in solving this little puzzle!
You're close, the key function should be:
key=lambda item: item[1]['c']
Rewritten to be more Pythonic:
sample = dict(sorted(sample.items(), key=lambda item: item[1]['c'], reverse=True))
(The dict constructor can take an iterable of item tuples)
string
Date,Open
2020-04-08,387.799988
2020-04-09,390.000000
my code
headers = self.str.split("\n")[0]
results = self.str.split("\n")[1:]
header_list = headers.split(",")
dict_share = []
dict_head = {}
for i, value in enumerate(header_list):
dict_head[i] = value
price_list = {}
for price in results:
price_str = price.split(",")
# print(price_str)
if 'null' not in price_str:
for i, temp in enumerate(price_str):
price_list[dict_head[i]] = temp
print(price_list)
dict_share.append(price_list)
print(dict_share)
output
{'Date': '2020-04-08', 'Open': '387.799988'}
[{'Date': '2020-04-08', 'Open': '387.799988'}]
{'Date': '2020-04-09', 'Open': '390.000000'}
[{'Date': '2020-04-09', 'Open': '390.000000'}, {'Date': '2020-04-09', 'Open': '390.000000'}]
I found all the dict of dict_share are always the last price_list list, the previous price_list was overwrite by the last one? how to avoid this?
I solved the problem myself, this is about deepcopy.your new vlaue must store in a new address,so you need copy.deepcopy()
for price in results:
price_str = price.split(",")
if 'null' not in price_str:
for i, temp in enumerate(price_str):
price_list[dict_head[i]] = temp
print(price_list)
new_price = copy.deepcopy(price_list)
dict_share.append(new_price)
print(dict_share)
I am new to python and am facing difficulties in dictionary. I am trying to store multiple values from excel into dictionary.
This is my input:
And i am trying to store in this way.
My expected output is:
d = [
{
"name":"dhdn",
"sub":["c","java","python"]
},
{
"name":"subbu",
"sub":["java","perl"]
}
]
I tried like this:
df_service = pd.read_excel(existing_excel_file, sheet_name='Sheet1')
df_service = df_service.replace(np.nan, "dummy")
print(df_service)
list1 = []
for i in range(0, len(df_service['name'])):
dict1 = {}
lst = []
if df_service['name'][i] != 'dummy':
dict1["name"] = df_service['name'][i]
lst.append(df_service['sub'][i])
else:
lst.append(df_service['sub'][i])
dict1["sub"] = lst
list1.append(dict1)
print(list1)
And what if the excel data is like given below:
What if we have data like this? How to create a dictionary for this?
Need some suggestion, not getting any idea.
df_service = df_service.fillna(method='ffill')
result = [{'name':k[0],'usn':k[1],'sub':v["sub"].tolist(),"marks":v["marks"].tolist()} for k,v in df_service.groupby(['name', 'usn'])]
pprint (result)
You can use pandas.DataFrame.fillna with the method='ffill' option. 'ffill' stands for 'forward fill' and will propagate last valid observation forward.
df_service = pd.read_excel(existing_excel_file, sheet_name='Sheet1')
df_service = df_service.fillna(method='ffill')
result = [{'name':k,'sub':g["sub"].tolist()} for k,g in df_service.groupby("name")]
print (result)
output:
[{'name': 'dhdn', 'sub': ['c', 'java', 'python']}, {'name': 'subbu', 'sub': ['java', 'perl']}]
Hi #ncica, I appreciate your answer, what if we have data like this? How to create a dictionary for this.
I have two python dicts:
payload = {"key1":{"a":"1"},"key2":{"b":"2","c":"3"}}
and
data = {"1":"John","2":"Jacob"}
I would like my output to be:
{"key1":{"a":"John"},"key2":{"b":"Jacob","c":""}}
Any method that I try correctly prints the values, but does not update the output dictionary.
You can do something like this using dict comprehension :
payload = {"key1":{"a":"1"},"key2":{"b":"2","c":"3"}}
data = {"1":"John","2":"Jacob"}
final = {k: {i:data[j] if j in data.keys() else "" for i, j in payload[k].items()} for k in payload}
print(final)
Output:
{'key2': {'b': 'Jacob', 'c': ''}, 'key1': {'a': 'John'}}
There is no single method for this I am aware of, but you can use:
for k, v in payload.viewitems():
payload[k] = {}
for kv, vv in v.viewitems():
payload[k][kv] = data.get(vv, "")
if you then inspect payload it has the contents you are after:
{'key2': {'c': '', 'b': 'Jacob'}, 'key1': {'a': 'John'}}