variable in string of dictionary in python - python-3.x

I have the following dictionary in python 3:
a = {'a': 'b:{androidString}'}
Try to define a variable and use it in the dictionary:
android = "androidString"
a = {'a': f'b:{{android}}'}
when:
print(a)
it says:
{'a': 'b:{android}'}
how to use the variable in the dictionary?

You're missing a curly bracket :
a = {'a': f'b:{{{android}}}'}
Output
{'a': 'b:{androidString}'}

Just use get method:
...
a.get('a')
get method takes two parameters first key name , second default
default returns Errors in default but you can change it to False
so when you try to get key doesn't exists it will return default
or you can use []:
...
a['a']
there are a lot options to get key of dictionary More info

Related

Python navigating nested dictionary

I have a nested dictionary that might have non-unique keys
I need to dynamically add/get key-value pairs on this dictionary by their key in string format
The string that is the key name is being read from keyboard input in string format
Given that string I have to find a key that matches it and do something with a corresponding key-value pair
The keys might be non-unique among different nesting levels
But they are unique on a single nesting level
For example, I have this dict:
MyDict = {'a': 1, 'b': 2}
Now, I get some input in string format that tells me to add one more nesting level with key 'c' and then fill it with a key-value pair 'a:3'. I do it like that:
last_edited_element = {'a': 3}
MyDict['c'] = last_edited_element
#MyDict is now {'a': 1, 'b': 2, 'c': {'a': 3}}
Then, I get an input that tells me to do something with a key-value pair that has 'a' key
I am given a rule that first I have to look up for 'a' key in a level that was edited last, then If nothing is found - go one level up. I store my last edited element in a variable last_edited_element.
The last edited element was {'a': 3}, so I do:
if 'a' in last_edited_element:
#do something with {'a': 3}
else:
#go one level up and look for 'a' key there
So the question is, how do I go one level up? I have {a: '3'} stored in a variable last_edited_element, I need to access the upper-level dictionary if any that contains last_edited_element, something like last_edited_element.get_parent_dictionary()
How do I do that?
So following up on my first comment, you could do this:
Initialize a top-level dict
Initialize all children to refer to their parent
Recursively search bottom-up until you find a key or None
example_dict = {'a': 1, 'b': 2, 'parent': None}
example_dict['c'] = {'a': 3, 'parent': example_dict}
def find_key(k, d):
if k in d:
return d[k]
elif d['parent'] is None:
return None
return find_key(k, d['parent'])
print(find_key('a', example_dict['c']))
> 3
print(find_key('b', example_dict['c']))
> 2

How to Convert 'dict_items' Object to List

I am loading data from json files using load method and then putting the items in a new python object.
obj_1 = json.load(file)
obj_2 = obj_1.items()
When I run the code in python2, type(obj_2) is list. But when I run in python 3, type(obj_2) is 'dict_items'. Because of that when I run following code:
sorted_items = sorted (obj_2[1][1]['string'])
I'm getting this error in python 3:
TypeError: 'dict_items' object does not support indexing
In python 2 it runs fine. How can I solve this issue in python 3? I have found some related questions about this but the answers doesn't solve my particular case. I have tried to use list(obj_2) but it causes key error.
json file format is something like this:
{
"item_1": {
"item_2": {
"string": 111111,
"string": 222222,
"string": 333333,
................
................
},
},
}
I want to sort the "item_2" contents according to the keys in ascending order.
simply
d = { .... }
l = list(d.items())
making a for loop here is the best option i can think of.
object_list = []
for key, value in obj_2:
entry = [key, value]
object_list.append(entry)
that would store the key and value in a list that is inside another list.
EDIT
Found a better way to do it!
my_dict = {"hello": "there", "how": "are you?"}
my_list = [[x, y] for x, y in my_dict.items()]
# out => [['hello', 'there'], ['how', 'are you?']]
Convert dict items (keys and values) to a list with one line of code. Example:
example_dictionary = {"a": 1, "b": 2, "c": 3}
dict_items_to_list = [*foo.keys(), *foo.values()]
print(dict_items_to_list)
>>> ['a', 'b', 'c', 1, 2, 3]

question about custom sorting using key argument in sorted()

I'm trying to gain some insight in to why I'm receiving an error message.
I'm trying to sort a dictionary using a custom function. I realize I can use lambda to achieve the same goal, as well as sorting the dictionary in to tuples first, but what I'm really trying to do is understand why my function isn't returning a list.
sample_dict = {"a":4,"b":2,"c":7,"d":9}
def all_values(x):
return list(x.values())
print(sorted(sample_dict, key = all_values))
Expecting for return list(x.values()) to return a list to be used in the sorted key argument, but instead, I'm given the error message:
AttributeError: 'str' object has no attribute 'values'
you mean to sort the keys according to the values.
The key function is meant to convert the dictionary key to something comparable (if you omit it, it's like passing an identity function, you're comparing on the dictionary key itself). You want to return the value from the key, so it's a dictionary access:
sample_dict = {"a":4,"b":2,"c":7,"d":9}
def all_values(x):
return sample_dict[x]
print(sorted(sample_dict, key = all_values))
You were expecting the dictionary to be passed in the key, which would have no interest at all. key must be different at each call sort does.
Using a lambda is of course shorter
print(sorted(sample_dict, key = lambda x: sample_dict[x]))
but passing a real function allows to insert side effects more easily:
def all_values(x):
print("key input",x)
return sample_dict[x]
with that you get an insight of what sort is doing (and the final result is printed by the main print statement):
key input b
key input a
key input c
key input d
['b', 'a', 'c', 'd']
and now you understand why list('b'.values()) failed.
I think you've been confused by the way key argument works.
Essentially, it maps a given function over all elements of your iterable, and then sorted sorts based on the outputs of the mapping.
In fact, when you sort sample_dict, you are sorting its keys, which are strings:
sample_dict = {"b":2, "c":7, "d":9, "a":4}
print(sorted(sample_dict))
# ['a', 'b', 'c', 'd']
and if I try to map all_values to this list of strings:
list(map(all_values, sample_dict))
# AttributeError: 'str' object has no attribute 'values'
all_values must get a string in input then, like #Jean-FrançoisFabre suggests:
def all_values(x):
return sample_dict[x]
print(sorted(sample_dict, key = all_values))
# ['b', 'a', 'c', 'd']

Problem arrives when use default value for dictionary

when using a default value for a dictionary the comprehensive loop show empty list when asked to iterate for all key items
from collections import defaultdict
dict = {'whiz':1,'beerus':2,'vegeta':3,'goku':4}
dict = defaultdict(lambda : 'picalo')
print ([key for key in dict])
[]
process finished with exit code 0
this code is run in pycharm
Welcome to SO. Please include a description of expected behavior with your questions, or you'll get answers like this:
That's because there's nothing in the dictionary, it just has a default value!
As far as I can tell the error you're making is you're replacing your dictionary, not giving it a default value.
I think what you're looking for is something like this:
from collections import defaultdict
my_dict = {'whiz': 1,'beerus': 2,'vegeta': 3,'goku': 4}
my_dict = defaultdict(lambda: 'picalo', **my_dict)
print(my_dict)
Notice how I named the variable my_dict instead of dict, that's because dict is the "built-in" dictionary type and generally shouldn't be overwritten (to prevent bugs down the line).

Deleting Dictionaries Keys with a For If Statement in Python 3

I feel very dumb asking this. How do I delete a keys in a dictionary with an if statement that references the values. When I do this:
newdict = {"a":1,"b":2,"c":3}
for (key,value) in newdict:
if value == 2:
del newdict[key]
print(newdict)
It throws this error:
line 3, in <module>
for (key,value) in newdict:
ValueError: not enough values to unpack (expected 2, got 1)
Thank you.
If you need to delete based on the items value, use the items() method or it'll give ValueError. But remember if you do so it'll give a RuntimeError. This happens because newdict.items() returns an iterator not a list. So, Convert newdict.items() to a list and it should work. Change a bit of above code like following -
for key,value in list(newdict.items()):
if value == 2:
del newdict[key]
output -
{'a': 1, 'c': 3}

Resources