I have a list of OrderedDict as follows:
power = [OrderedDict([('i', '1'), ('p', '-9.11')]), OrderedDict([('i', '2'), ('p', '-9.11')]), OrderedDict([('i', '3'), ('p', '-9.1')]), OrderedDict([('i', '4'), ('p', '-9.1')]), OrderedDict([('i', '5'), ('p', '-9.1')]), OrderedDict([('i', '6'), ('p', '-9.1')]), OrderedDict([('i', '7'), ('p', '-9.09')]), OrderedDict([('i', '8'), ('p', '-9.09')]), OrderedDict([('i', '9'), ('p', '-9.09')]), OrderedDict([('i', '10'), ('p', '-9.09')]), OrderedDict([('i', '11'), ('p', '-9.08')]), OrderedDict([('i', '12')]]
I want the get the 'i' number such as 1,2,3 and also the 'p' value '-9.11', '-9.1' .. I have tried
for i,j in power:
print(i,":", j)
but it returns i:p
Any idea how to execute that?
CodePudding user response:
You could try:
for i, j in (d.values() for d in power):
print(f'{i} : {j}')
Assuming each OrederedDict
in power
has a length of 2.
CodePudding user response:
There are no tuples in your OrderedDict
. When you do call OrderedDict(iterable)
(e.g. in your case the iterable
is a list
), it expects that each element of iterable
gives you a key-value pair. So in your case, each element of the list is a tuple, and the first element of that tuple is the key, the second item is the value to set in the OrderedDict
.
When you do for item in power
, each item
is an OrderedDict
.
When you try to unpack it in that same line with for i, j in power
, the OrderedDict
called item
gets unpacked into the variables i
and j
. When you unpack a dict, you get its keys, so the variable i
gets the first key (which is the string "i"
), and the variable p
gets the second key (which is the string "p"
). You could unpack the values using ssp's answer, but I suggest you should actually access the keys of the dict.
Once you have item
, you can simply access its keys using item[key]
. So do:
for item in power:
print(item["i"], ":", item["p"])
If you want to create a new dictionary where the values of the i
key are keys and the values of the p
key are values, do:
d = dict()
for item in power:
key = item["i"]
value = item["p"]
d[key] = value
Or, as a dict comprehension:
d = {item["i"]: item["p"] for item in power}
Which gives:
{'1': '-9.11',
'2': '-9.11',
'3': '-9.1',
'4': '-9.1',
'5': '-9.1',
'6': '-9.1',
'7': '-9.09',
'8': '-9.09',
'9': '-9.09',
'10': '-9.09',
'11': '-9.08'}
If you want the keys to be integers and the values to be floats, explicitly convert them:
d = {int(item["i"]): float(item["p"]) for item in power}