Skip to content

class UDict[KT, VT, CDV]

class UDict(dictionary: AnyDict[KT, VT]) # (1)!
class UDict(dictionary: AnyDict[KT, VT], *, default: CDV)
class UDict(**kwargs: VT)
class UDict(*, default: CDV, **kwargs: VT)
  1. AnyDict[KT, VT] = LikeDict[KT, VT] | dict[KT, VT]. In UDict

    Note

    LikeDict[KT, VT] is type which has __getitem__, __setitem__, __delitem__ and get() methods. UDict is LikeDict.

    Read about AnyDict and LikeDict


UDict as generic

You can use UDict as Generic, because of it, there are 3 TypeVars: KT, VT, CDV.

KT and VT are key type and value type. In inbuilt dict there are KT and VT type vars. CDV is class default value.

In this documentation KT, VT and CDV will be used in methods.

Create UDict object. If default, when not existent keys is given in getting item, method will return default.

Example

d = UDict(hello=world, hi=python, default=10)

(property, settable) dictionary: dict[KT, VT]

UDict's dictionary.

Example

print(d.dictionary)
d.dictionary = {4: 'world'}

Tip

You can use UDict to set dictionary

Example

d.dictionary = UDict({1: 7})

(property, settable) keys: list[KT]

UDict's keys

Example

print(d.keys)
d.keys = [1, 2]

Tip

You can use tuples to set keys

Example

d.keys = 1, 2

(property, settable) values: list[VT]

UDict's values

Example

print(d.values)
d.values = [7, 2]

Tip

You can use tuples to set values

Example

d.values = 7, 2

(property, settable) items: list[tuple[KT, VT]]

UDict's items.

Example

print(d.items)
d.items = [(1, 7), (2, 2)]

Tip

You can use tuples to set items or you can use tuples or lists with lists

Example

d.items = (1, 7), (2, 2)
d.items = [1, 7], [2, 2]

(property, settable) default: CDV

UDict's default value

Example

print(d.default)
d.default = 'null'

reverse() -> UDict[KT, VT, CDV]

Reverses UDict and returns it. (1)

  1. How UDict is being reversing?

    Just is being reversing items
    u{'hello': 1, 'hi': 2} -> u{'hi': 2, 'hello': 1} (reversed)

Warning

reverse() edits UDict. If you don't want to reverse UDict use reversed() method instead.

Example

d.reverse()
print(d) # prints reversed UDict

reversed() -> UDict[KT, VT, CDV]

Returns reversed UDict

Example

print(d.reversed())

Get reversed UDict with inbuilt reversed() and ~ operator

You can get reversed UDict with inbuilt reversed() and with invert operator (~).

Example

print(~d)
print(reversed(d))
print(d.reversed() == reversed(d)) # True

Read more about reversed() and ~ support in UDict

sort() -> UDict[KT, VT, CDV]

Sorts UDict and returns it. (1)

  1. How UDict is being sorting?

    Just are being sorting items by keys.
    u{'b': 1, 'a': 2} -> u{'a': 2, 'b': 1} (sorted)

Warning

sort() edits UDict. If you don't want to sort UDict use sorted() method instead.

Example

print(d.sort())

sorted() -> UDict[KT, VT, CDV]

Returns sorted UDict

Example

print(d.sorted())

get()

def get(*, key: KT) -> VT | CDV
def get(*, key: KT, default: DV) -> VT | DV
def get(*, index: int) -> VT | CDV
def get(*, index: int, default: DV) -> VT | DV
def get(*, value: VT) -> KT | CDV
def get(*, value: VT, default: DV) -> KT | DV

Using more than 1 argument

If you use 0 or 2 or 3 of this arguments (key, index, value), method will raise ValueError

Arguments:

key: KT

UDict value's key to find.

Example

print(d.get(key='key')) # same that d['key']

index: int

UDict value's index to find

Warning

Indexes are starting from 1. Index of first element of UDict is 1.

index argument more than UDict length

If you use index argument make sure that index are less than UDict length. Otherwise get() will raise IndexError

Example

print(d.get(index=2)) # second value of UDict

value: VT

UDict key's value to find

Example

print(d.get(value=1)) # if d = UDict{'hello': 1}, this will be 'hello'

default: DV

Default value, if the result was not found. If not provided, then default is UDict.default property.

Example

d = UDict(hello=1, hi=2, default=-1)
print(d.get(key='hell')) # -1
print(d.get(key='hell', default=None)) # None

is_empty() -> bool

Returns True if the UDict is empty (len(UDict) == 0), otherwise returns False.

Example

    d = UDict(hello=1)
    d2 = UDict()
    print(d.is_empty()) # False
    print(d2.is_empty()) # True

Convert UDict to bool

You can convert UDict to bool or use UDict in if statement. If UDict.is_empty() == True then bool(UDict) is False and by contrast. Same in if because of if x is the equivalent of if bool(x)

Example

# d is from code above
print(bool(d)) # True
if d:
    print("d is True") # d is True

Magic methods

Currently, UDict supports all these magic methods:

__call__(func: Callable[[KT, VT], VT]) -> UDict[KT, VT, CDV]

Returns new UDict, but all values generated with func function. First argument: key, second: value.

Arguments:

func: (KT, VT) -> VT

First argument of function is key, second is value. Returns new value

Example

def f(k, v):
    return v * 2
d = d(f) # multiply all values by 2

__neg__() -> UDict[KT, int | float, CDV]

Negates all values (if they support the - operator) to their opposite numbers.

Example

d = UDict(hello=1, hi=-2)
print(-d) # u{'hello': -1, 'hi': 2}

__invert__() -> UDict[KT, VT, CDV]

The equivalent of reversed()

Example

print(~d)

__reversed__() -> UDict[KT, VT, CDV]

The equivalent of reversed()

Example

print(reversed(d))

__getitem__(key: KT | int | slice) -> UDict[KT, VT, DV] | VT

Returns the value for a single key, or a UDict for multiple keys provided with a slice.

Indexes starting at 1.

Arguments:

key: KT | int | slice

Value's key or index to get or values's indexes slice to get.

Example

print(d['hello'])
print(d[1:2])

Using indexes

You can also use indexes in __getitem__().

Failure

Keep in mind that indexes are using after the keys with the given value were not found.

Example

If you have 1 key, d[1] syntax will use 1 how key, not index. If you want to use index in all ways, use get() instead.

Example

d = UDict(hello=1, hi=9)
print(d[2]) # 9

__setitem__(key: KT | int | slice, value: VT | list[VT] | tuple[VT])

Sets the value or values for the given key or keys.

key: KT | int | slice

Value's key or keys to set. This argument is the same with key argument in __getitem__() method

value: VT | list[VT] | tuple[VT]

Value or values to set.

Example

d = UDict(hello=2, hi=1)
d[2] = 'hello'
print(d['hi']) # 'hello'
d[:] = 'hello', 'world'
print(d) # u{'hello': 'hello', 'hi': 'world'}

__delitem__(key: KT | int | slice)

Deletes items with the given key or keys.

key: KT | int | slice

Item's key or keys to delete. This argument is the same with key argument in __getitem__() method.

__len__() -> int

Returns the length of the UDict.

Example

d = UDict(hello=1, hi=2) print(len(d)) # 2

__iter__() -> Iterator[tuple[KT, VT]]

Iterate over the UDict. The equivalent of items.__iter__().

Example

for k, v in d:
    print(f"Key: {k}\nValue: {v}") # Prints all keys and its values.

__bool__() -> bool

Returns whether the UDict is not empty. The equivalent of not is_empty()

Example

print(bool(d))
if d:
    print("D is not empty!")

__contains__(item: tuple[KT, VT] | list[KT | VT] | KT) -> bool

Checks whether the item or key is in the UDict.

Arguments:

item: tuple[KT, VT] | list[KT | VT] | KT

Item or item's key.

Example

if ('key', 'value') in d: ...
if ['key', 'value'] in d: ...
if 'key' in d: ...

__repr__() -> str

Returns the string representation of the UDict. This allows the UDict to be used in print() and repr().

Example

d = UDict(hello=1)
print(d) # u{'hello': 1}
print(repr(d)) # Same

__hash__() -> int

Returns the hash for repr(UDict). The equivalent of repr(UDict).__hash__().

__cmp__(other: dict[KT, VT] | UDict[KT, VT, CDV]) -> int

Used by @cmp_generator, which generates comparison magic methods like ==, !=, >, >=, <, <= operators.

Comparing UDicts involves comparing their lengths, except for __eq__().

Example

d = UDict(hello=1)
d2 = UDict(hello=1, hi=2)
print(d != d2) # True
print(d < d2) # True
print(d > d2) # False

__eq__(other: dict[KT, VT] | UDict[KT, VT, CDV]) -> bool

Checks whether UDicts are the same. (Overrides generated by @cmp_generator magic method)

Example

d = UDict(hello=1)
d2 = UDict(hello=1, hi=2)
print(d == d2) # False
print(d == d) # True

Tip

You can use dict to compare with UDict. Method will automatically generate UDict from this dict

print(d == {'hello': 1}) # True

__add__(other: dict[KT, VT] | UDict[KT, VT, CDV]) -> UDict[KT, VT, CDV]

Adds the dictionary or UDict's dictionary to the UDict's dictionary. This method also has r and i versions (+=).

Example

print(d + {'hi': 2})
print({'hi': 2} + d)
d += {'hi': 2}

__sub__(other: dict[KT, VT] | UDict[KT, VT, CDV]) -> UDict[KT, VT, CDV]

Subtracts the dictionary or UDict's dictionary from the UDict's dictionary. This method also has r and i versions (-=).

Example

d = UDict(hello=1, hi=2)
print(d - {'hello': 1}) # u{'hi': 2}
d -= {'hello': 1}
print(d) # Same

__mul__(other: dict[KT, float | int] | UDict[KT, float | int, DV] | float | int) -> UDict[KT, SupportsMul, CDV]

Multiply all values by other, if other is int or float. Multiply values with keys equals to other keys by other values, if other is dict or UDict. This method also have r and i version (*=)

Warning

Make sure that your UDict's values supports multiply operator (*)

Example

d = UDict(hello=1, hi=2)
print(d * 2) # {'hello': 2, 'hi': 4}
print(d * {'hi': 3}) # {'hello': 1, 'hi': 6}

__truediv__(other: dict[KT, float | int] | UDict[KT, float | int, DV] | float | int) -> UDict[KT, SupportsTrueDiv, CDV]

Same that __mul__(), but with divide operator (/).

Warning

Make sure that your UDict's values supports divide operator (/)

Example

d = UDict(hello=1, hi=2)
print(d / 2) # {'hello': 0.5, 'hi': 1}
print(d / {'hi': 4}) # {'hello': 1, 'hi': 0.5}

Examples

Init

Example

d = UDict({'id': 2, 'content': 'hello, world'})
# for string keys you can use this way:
d = UDict(id=2, content='hello, world')

Example

You can also define default value for items when you use item's getter:

d = UDict(id=2, content='hello, world', default=0)

Get items

For getting items you should use the way you use in lists and dicts: use UDict[key] syntax:

Example

d['id'] # 2

Tip

You can also use index of key or slice of indexes of keys:

Warning

In this class first index is 1

Example

d[1] # 2
d[:] # u{'id': 2, 'content': 'hello, world'} (UDict object)

You can also use get() method. You can get item by its key using key kwarg, you can get item by its index using index kwarg, and you get item key by its value using value kwarg.

You can define default only for this calling

d = UDict({2: 3, 1: 4}, default=None)
d[2] # 3
d.get(index=2) # 4
d.get(key=1) # also 4
d.get(value=3) # 2

d.get(key=3) # None
d.get(key=3, default='null') # 'null'

Set items

For setting items you should use the way you use in lists and dicts: use UDict[key] = value syntax:

Example

d['id'] = 3

You can use indexes and slices

d[1] = 2
d[2:6:2] = 8
d[:3] = 1, 2, 3

Delete items

For deleting items you should use the way you use in lists and dicts: use del UDict[key] syntax:

Example

del d['id']

You can use indexes and slices

del d[1]
del d[:] # all UDict will become empty

Get length of dict

You can get length of dict using inbuilt len() function

d = UDict(hello=1, hi=2)
len(d) # 2

Iterate dict: keys, values, items properties

You can iterate dict using for key, value in UDict syntax.

d = UDict(hello=1, hi=2)
for key, value in d:
    print(key, value)

# out:
# hello 1
# hi 2

Also, you can iterate items property for this result

for key, value in d.items:
    ...

If you want iterate only all keys or values, use keys or values properties

for key in d.keys:
    ...

for value in d.values:
    ...

Check that dict is empty or not empty

You can use is_empty() method to check that UDict is empty

d = UDict()
print(d.is_empty()) # True

d['hello'] = 'world'
print(d.is_empty()) # False

You also can use if UDict or bool(UDict) syntax

d = UDict()
print(bool(d)) # False

d['hello'] = 'world'
print(bool(d)) # True

if d:
    print('True!')

# out:
# True!

Check that key or item in dict

You can check that key in dict

d = UDict(hi=1, hello=2)

print('hi' in d) # True
print('hii' in d) # False

You can also check that item in dict

d = UDict(hi=1, hello=2)

print(('hi', 1) in d) # True
print(('hi', 11) in d) # False

Using repr() and print()

Because print() uses repr(), you can directly print UDict objects

d = UDict(hi=1, hello=2)
print(d) # u{'hi': 1, 'hello': 2}
print(repr(d)) # u{'hi': 1, 'hello': 2}

Comparing dicts

You can compare UDicts using inbuilt compare operators (==, !=, >, >=, <, <=)

Note

When you use equal and not equal compare operator, dicts are comparing by its items and length, but in other compare operators dicts are comparing only by its length.

For example, d > d2 -> len(d) > len(d2), etc.

d = UDict(hi=1, hello=2)
d2 = UDict(hi=1, hello=2)
d3 = UDict(hi=1, hello=2, world=3)

print(d == d2) # True
print(d != d2) # False
print(d < d3) # True
print(d <= d3) # True
print(d3 > d) # True
print(d3 >= d) # True

Math operations

You can use inbuilt math operators (+, -, *, /, +=, -=, *=, /=) with UDicts

Note

When you use sum and sub math operators (+, -) dicts are summing or subtracting, but when you use other math operators dict will be multiplying or dividing by integer or dict.

When dict it works like this:

d * {'hello': 2, 'hi': 0.5} -> 
d['hello'] * 2
d['hi'] * 0.5
d = UDict(hi=1, hello=2)
print(d + {'world': 3}) # u{'hi': 1, 'hello': 2, 'world': 3}
print(d - {'hello': 2}) # u{'hi': 1}

print(d * 2) # u{'hi': 2, 'hello': 4}
print(d * {'hi': 2}) # u{'hi': 2, 'hello': 2}

print(d / 2) # u{'hi': 0.5, 'hello': 1}
print(d / {'hi': 2}) # u{'hi': 0.5, 'hello': 2}

Negative dict

You can use unary minus with dicts

d = UDict(hi=1, hello=2)
print(-d) # u{'hi': -1, 'hello': -2}

Reverse dict

You can reverse dict using reverse() or reversed() method

When you use reverse(), dict updates in contrast to reversed(). Be careful!

# reverse()
d = UDict(b=1, a=2)
print(d.reverse()) # u{'a': 2, 'b': 1}
print(d) # u{'a': 2, 'b': 1}

# reversed()
d = UDict(b=1, a=2)
print(d.reversed()) # u{'a': 2, 'b': 1}
print(d) # u{'b': 1, 'a': 2}
d.reverse()
d.reversed()

You can use ~ operator and reversed() class. They are equivalents of UDict.reversed()

~d
reversed(d)

Sort dict

You can use sort() and sorted() methods for sorting UDict

sort() is updating dict, sorted() - isn't. Be careful!

# sort()
d = UDict(b=1, a=2)
print(d.sort()) # u{'a': 2, 'b': 1}
print(d) # u{'a': 2, 'b': 1}

# sorted()
d = UDict(b=1, a=2)
print(d.sorted()) # u{'a': 2, 'b': 1}
print(d) # u{'b': 1, 'a': 2}
d.sort()
d.sorted()